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.

 

一开始用hashmap做的,很慢。

public class Solution {
    public int firstUniqChar(String s) {
        if (s == null) {
            return -1;
        }
        Map<Character, Integer> hm = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            if (hm.containsKey(s.charAt(i))) {
                hm.put(s.charAt(i), hm.get(s.charAt(i)) + 1);
            } else {
                hm.put(s.charAt(i), 0);
            }
        }
        for (int i = 0; i < s.length(); i++) {
            if (hm.get(s.charAt(i)) == 0) {
                return i;
            }
        }
        return -1;
    }
}

 

后来发现可以用数组做,就很快了。记得应该做过,怎么就不记得了呢。。。

public class Solution {
    public int firstUniqChar(String s) {
        if (s == null) {
            return -1;
        }
        int[] f = new int[26];
        for (int i = 0; i < s.length(); i++) {
            f[s.charAt(i) - 'a']++;
        }
        for (int i = 0; i < s.length(); i++) {
            if (f[s.charAt(i) - 'a'] == 1) {
                return i;
            }
        }
        return -1;
    }
}

 

其实不是很懂为什么时间复杂度都一样,却从120多ms变成30ms。

附上C++做法:

class Solution {
public:
    int firstUniqChar(string s) {
        unordered_map<char, int> m;
        for (auto &c : s) {
            m[c]++;
        }
        for (int i = 0; i < s.size(); i++) {
            if (m[s[i]] == 1) {
                return i;
            }
        }
        return -1;
    }
};

 

如果string过长的话,就遍历hashmap而不是string

class Solution {
public:
    int firstUniqChar(string s) {
        unordered_map<char, pair<int, int>> m;
        int index = s.size();
        for (int i = 0; i < s.size(); i++) {
            m[s[i]].first++;
            m[s[i]].second = i;
        }
        for (auto &p : m) {
            if (p.second.first == 1) {
                index = min(index, p.second.second);
            }
        }
        return index == s.size() ? -1 : index;
    }
};

 

数组记频率法:
class Solution {
public:
    int firstUniqChar(string s) {
       int f[26] = {0};
       for (int i = 0; i < s.size(); i++) {
            f[s[i] - 'a']++;
        }
        for (int i = 0; i < s.size(); i++) {
            if (f[s[i] - 'a'] == 1) {
                return i;
            }
        }
        return -1;
    }
};

 

posted @ 2017-06-11 04:12  璨璨要好好学习  阅读(173)  评论(0编辑  收藏  举报