First Unique Character in a String
Posted 璨璨要好好学习
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; } };
以上是关于First Unique Character in a String的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 387. First Unique Character in a String
209 First Unique Character in a String
first-unique-character-in-a-string
LeetCode(387)First Unique Character in a String