Leetcode: NO.387 字串中的第一個唯一字元
阿新 • • 發佈:2020-12-25
技術標籤:演算法
題目
給定一個字串,找到它的第一個不重複的字元,並返回它的索引。如果不存在,則返回 -1。
示例:
s = "leetcode"
返回 0
s = "loveleetcode"
返回 2
提示:你可以假定該字串只包含小寫字母。
連結:https://leetcode-cn.com/problems/first-unique-character-in-a-string
解題記錄
- 先統計個數
- 然後返回第一個只有一個的索引
/**
* @author: ffzs
* @Date: 2020/12/23 上午8:25
*/
public class Solution {
public int firstUniqChar(String s) {
char[] chars = s.toCharArray();
int[] counter = new int[26];
for (char c : chars) {
counter[c-'a']++;
}
for (int i = 0; i < chars.length; i++) {
if (counter[chars[i]-'a'] == 1) return i;
}
return -1;
}
}