一:解题思路
方法一:先遍历一遍字符串,记录每个字母出现的次数,然后再遍历一遍字符串,查看第一次出现只出现一次的字母下标。这种方法需要遍历字符串2次,如果字符串很长的话,那么就会比较耗时。Time:O(n),Space:O(n)
方法二:遍历一遍字符串,记录每个字母出现的次数,同时记录每个字母出现的下标,最后在只出现一次的所有字母中,找出第一次出现一次的那个字母的下标。
二:完整代码示例 (C++版和Java版)
方法一C++:
class Solution { public: int firstUniqChar(string s) { if (s.size() == 0) return -1; vector<int> count(26,0); for (int i = 0; i < s.size(); i++) { count[s[i] - ‘a‘]++; } for (int i = 0; i < s.size(); i++) { if (count[s[i] - ‘a‘] == 1) return i; } return -1; } };
方法一Java:
class Solution { public int firstUniqChar(String s) { if(s==null||s.length()==0) return -1; int[] count=new int[26]; for(int i=0;i<s.length();i++) count[s.charAt(i)-‘a‘]++; for(int i=0;i<s.length();i++) if(count[s.charAt(i)-‘a‘]==1) return i; return -1; } }
方法二C++:
class Solution { public: int min(int a, int b) { return a < b ? a : b; } int firstUniqChar(string s) { if (s.size() == 0) return -1; vector<int> count(26,0); vector<int> pos(26,-1); for (int i = 0; i < s.size(); i++) { int idx = s[i] - ‘a‘; count[idx]++; if (pos[idx] == -1) pos[idx] = i; } int maxValue = 2147483647; int firstPos = maxValue; for (int i = 0; i < 26; i++) if (count[i] == 1) firstPos = min(firstPos,pos[i]); return firstPos == maxValue ? -1 : firstPos; } };
方法二Java:
class Solution { public int firstUniqChar(String s) { if(s==null||s.length()==0) return -1; int[] count=new int[26]; int[] pos=new int[26]; Arrays.fill(pos,-1); for(int i=0;i<s.length();i++) { int idx=s.charAt(i)-‘a‘; count[idx]++; if(pos[idx]==-1) pos[idx]=i; } int firstPos=Integer.MAX_VALUE; for(int i=0;i<26;i++) if(count[i]==1) firstPos=Math.min(firstPos,pos[i]); return firstPos==Integer.MAX_VALUE?-1:firstPos; } }
p59 第一个只出现一次的字符 (leetcode 387)
原文:https://www.cnblogs.com/repinkply/p/12520236.html