
這題需要判斷判斷第一個沒有重複的文字是在哪個位置。
LeetCode 題目連結
https://leetcode.com/problems/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.
Accept 作法
Runtime: 202 ms
Memory: 114.8 MB
Java 程式碼
class Solution {
public int firstUniqChar(String s) {
HashMap map = new HashMap();
for(int i = 0;i<s.length();i++){
if(map.containsKey(String.valueOf(s.charAt(i)))){
int count =(int) map.get(String.valueOf(s.charAt(i)));
count+=1;
map.put(String.valueOf(s.charAt(i)),count);
}else{
map.put(String.valueOf(s.charAt(i)),0);
}
}
for(int i = 0;i<s.length();i++){
if(map.containsKey(String.valueOf(s.charAt(i)))){
int count =(int) map.get(String.valueOf(s.charAt(i)));
if(count == 0){
return i;
}
}
}
return -1;
}
}
更多 LeetCode 相關資源
複習程式面試書籍
除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。
需要的話可以看看,寫得很仔細。
沒有留言:
張貼留言