Given a string, find the first non-repeating character in it and return its index.
If it doesn't exist, return -1.
문자열이 주어지면, 반복되지 않는 가장 첫번째 문자 찾아 인덱스를 반환하라.
만약 존재하지 않는다면, -1을 반환하라.
풀이 방법
1. 총 26개 알파벳의 카운트 값을 담을 배열 alpha를 선언한다.
2. 문자열의 길이만큼 반복문을 수행하며, 한 글자씩 파싱한다.
3. 파싱된 문자의 아스키코드 값 - 97을 하여, 해당 알파벳의 카운팅을 수행한다.
4. 다시 문자열의 길이만큼 반복문을 수행하며, 카운트가 1인 알파벳의 인덱스를 반환한다.
5. 카운트가 1인 알파벳이 없을 경우, 반복문을 마친 후 -1 값을 반환한다.
class Solution {
public int firstUniqChar(String s) {
char[] alpha = new char[26];
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
int num = c - 97;
alpha[num]++;
}
for(int i=0; i<s.length(); i++) {
if(alpha[s.charAt(i)-97] == 1)
return i;
}
return -1;
}
}
'알고리즘 > LeetCode' 카테고리의 다른 글
[JAVA] LeetCode 350 - Intersection of Two Arrays II (0) | 2020.12.01 |
---|---|
[JAVA] LeetCode 268 - Missing Number (0) | 2020.11.30 |
[JAVA] LeetCode 118 - Pascal's Triangle (0) | 2020.11.27 |
[JAVA] LeetCode 21 - Merge Two Sorted Lists (0) | 2020.11.23 |
[JAVA] LeetCode 122 - Best Time to Buy and Sell Stock II (0) | 2020.11.22 |