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.
找到第一个无重复的字符,返回其索引
C++(55ms):
1 class Solution { 2 public: 3 int firstUniqChar(string s) { 4 vector<int> vec(126 , 0) ; 5 int len = s.size() ; 6 for (int i = 0 ; i < len ; i++){ 7 vec[s[i]]++ ; 8 } 9 for (int i = 0 ; i < len ; i++){ 10 if (vec[s[i]] == 1){ 11 return i ; 12 } 13 } 14 return -1 ; 15 } 16 };
C++(106ms): 使用unordered_map 时间为73ms
1 class Solution { 2 public: 3 int firstUniqChar(string s) { 4 map<char,int> mp ; 5 for (int i = 0; i < s.size();i++ ){ 6 mp[s[i]]++; 7 } 8 for (int i = 0; i < s.size();i++ ){ 9 if (mp[s[i]] == 1) 10 return i ; 11 } 12 return -1 ; 13 } 14 };
java(38ms):
1 public class Solution { 2 public int firstUniqChar(String s) { 3 char[] a = s.toCharArray(); 4 5 for(int i=0; i<a.length;i++){ 6 if(s.indexOf(a[i])==s.lastIndexOf(a[i])){return i;} 7 } 8 return -1; 9 } 10 }