[LeetCode] 387. First Unique Character in a String

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

题目:输入一个字符串,找出最先出现的不重复字符,返回这个字符的index,如果不存在则返回-1。假设输入的字符串只包含小写字母。

实现思路1:用HashMap统计每个字符出现的频率,然后找出频率是1的字符并返回这个字符的index,如果不存在就返回-1。这种方法的时间复杂度是O(n),空间复杂度是O(n)。

class Solution {
    public int firstUniqChar(String s) {
        if (s == null) throw new IllegalArgumentException("argument is null");
        Map map = new HashMap<>();
        for (char c : s.toCharArray()) {
            if (!map.containsKey(c))
                map.put(c, 1);
            else
                map.put(c, map.get(c) + 1);
        }
        for (int i = 0; i < s.length(); i++)
            if (map.get(s.charAt(i)) == 1)
                return i;
        return -1;
    }
}

实现思路1的改进:由于题目说明了输入的字符串只有小写字母,因此可以用一个char[]数组来统计每个字符出现的频率,其余思路不变。这种方法的时间复杂度是仍然是O(n),但空间复杂度是O(1)。

class Solution {
    public int firstUniqChar(String s) {
        if (s == null) throw new IllegalArgumentException("argument is null");
        char[] table = new char[26];
        for (char c : s.toCharArray())
            table[c - 'a'] += 1;
        for (int i = 0; i < s.length(); i++)
            if (table[s.charAt(i) - 'a'] == 1)
                return i;
        return -1;
    }
}

实现思路2:利用String的indexOf和lastIndexOf方法,即如果字符x首次出现的index等于最后出现的index,就说明这个字符只出现一次。这种实现方法的代码虽然变得更简洁,但时间复杂度却是O(n^2)。

class Solution {
    public int firstUniqChar(String s) {
        if (s == null) throw new IllegalArgumentException("argument is null");
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (s.indexOf(c) == s.lastIndexOf(c))
                return i;
        }
        return -1;
    }
}

参考资料:

https://leetcode.com/problems/first-unique-character-in-a-string/discuss/86348/Java-7-lines-solution-29ms

https://leetcode.com/problems/first-unique-character-in-a-string/discuss/86359/my-4-lines-Java-solution

你可能感兴趣的:(LeetCode)