Leetcode 387 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.(小寫字母)

 

首先這里假設只有小寫字母,自然想到開一個大小為26的數組,保存每個字母出現的次數,然后在掃描一次字符串,判斷出現次數是否為1,若是則直接返回小標,掃描結束后若還沒有返回,說明沒有字符只出現一次,返回1.

 1 int firstUniqChar(char* s) {
 2     int m[26] = {0}, len = strlen(s), i;
 3     for(i = 0; i < len; i++){
 4         m[s[i] - 'a']++;
 5     }
 6     for(i = 0; i < len; i++){
 7         if(m[s[i] - 'a'] == 1)
 8             return i;
 9     }
10     return -1;
11 }

如果沒有假設只包含小寫字母,則可以用map

 1 class Solution {
 2 public:
 3     int firstUniqChar(string s) {
 4         int len = s.length(), i;
 5         map<char, int> map1;
 6         for(i = 0; i < len; i++){
 7             map1[s[i]]++;
 8         }
 9         for(i = 0; i < len; i++){
10            if(map1[s[i]] == 1)
11                 return i;
12         }
13         return -1;
14     }
15 };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM