【初級算法】14. 字符串中的第一個唯一字符
阿新 • • 發佈:2018-05-03
字符串 如果 str 英文字母 turn size span div UC
題目:
給定一個字符串,找到它的第一個不重復的字符,並返回它的索引。如果不存在,則返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 註意事項:您可以假定該字符串只包含小寫字母。
1.解題思路:
關於本題解題思路很簡單,直接統計相關的26個英文字母的個數即可,非常簡單。
typedef struct counter{ int id; int cnt; }counter; class Solution { public: int firstUniqChar(string s) { counter mycnt[26]; int minRes = s.size(); /*intial*/ memset(mycnt,0,sizeof(counter)*26); for(int i = 0;i < s.size();++i){ mycnt[s[i]-‘a‘].id = i; mycnt[s[i]-‘a‘].cnt += 1; } for(int i = 0;i < 26; ++i){ if(mycnt[i].cnt == 1){ minRes = min(mycnt[i].id,minRes); } } if(minRes == s.size()){ return -1; } return minRes; } };
【初級算法】14. 字符串中的第一個唯一字符