[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<Character, Integer> 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值