• LeetCode 387---First Unique Character in a String


    Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

    Example 1:

    Input: s = “leetcode”
    Output: 0

    Example 2:

    Input: s = “loveleetcode”
    Output: 2

    Example 3:

    Input: s = “aabb”
    Output: -1

    Constraints:

    • 1 <= s.length <= 105
    • s onsists of only lowercase English letters.

    Solution1 using java API indexOf

    class Solution {
        public int firstUniqChar(String s) {
            for (int i = 0; i < s.length(); i++) {
                if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i))) {
                    return i;
                }
            }
            return -1;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    Solution2 using HashMap

    class Solution {
        public int firstUniqChar(String s) {
            int res = -1;
            HashMap<Character, Integer> map1 = new HashMap<>();
            for (int i = 0; i < s.length(); i++) {
                if (map1.get(s.charAt(i)) == null) {
                    map1.put(s.charAt(i), 1);
                } else {
                    map1.put(s.charAt(i), map1.get(s.charAt(i)) + 1);
                }
            }
            for (int j = 0; j < s.length(); j++) {
                if (map1.get(s.charAt(j)) == 1) {
                    res = j;
                    break;
                }
            }
            return res;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    Solution3 dual circulation

    class Solution {
        public int firstUniqChar(String s) {
            int res = -1;
            boolean isDouble = false;
            for (int i = 0; i < s.length(); i++) {
                for (int j = 0; j < s.length(); j++) {
                    if (i == j) {
                        continue;
                    }
                    if (s.charAt(i) == s.charAt(j)) {
                        isDouble = true;
                        break;
                    }
                }
                if (isDouble) {
                    isDouble = false;
                } else {
                    res = i;
                    break;
                }
            }
            return res;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
  • 相关阅读:
    2022年简历石沉大海,别投了,软件测试岗位饱和了....
    设计模式【六】:适配器
    聊聊HttpClient的close
    x64dbg 2022 最新版编译方法
    靠这份啃了 58 天的「Java 进阶核心知识集」抖音三面
    一、CC2530开发环境搭建
    Java泛型的总结
    记录了解php8-JIT
    编译原理第五章——语法分析(中)LL(1)分析
    LayUI之CRUD
  • 原文地址:https://blog.csdn.net/liuwg1226/article/details/126683443