알고리즘 문제풀이/leetcode
[leetcode 387] First Unique Character in a String
m2162003
2020. 11. 14. 16:59
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
Examples:
s = "leetcode" return 0. s = "loveleetcode" return 2.
문제 풀이:
해쉬맵 사용. 문자열 전체를 돌면서 카운트 진행
카운트가 처음으로 1이 나오는 문자열 인덱스를 리턴
class Solution {
public int firstUniqChar(String s) {
int result = -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 result;
}
}