Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발 일지

387. First Unique Character in a String (문자열의 첫 번째 고유 문자) C# 본문

코딩 테스트/LeetCode

387. First Unique Character in a String (문자열의 첫 번째 고유 문자) C#

포카리tea 2022. 11. 18. 02:17

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

문자열 s가 주어질 때, 그 안에서 반복되지 않는 첫 번째 문자를 찾고 해당 인덱스를 반환합니다. 존재하지 않으면 -1을 반환합니다.

예시 1:

입력: s = "leetcode"
출력: 0

예시 2:

입력: s = "loveleetcode"
출력: 2

예시 3:

입력: s = "aabb"
출력: -1

 

조건: 

  • s는 영문 소문자로만 구성되어 있습니다.

정답:

public class Solution {
    public int FirstUniqChar(string s) {
        Boolean[] isChecked = new Boolean[26];
        for (int i = 0; i < s.Length; i++) 
        {
            int index = s[i] - 'a';
            if (isChecked[index]) continue;
            if (!isChecked[index] && s.IndexOf(s[i], i + 1) < 0) 
            {
                return i;
            }
            isChecked[index] = true;
        }
        
        return -1;
    }
}

해설: 

bool 배열을 만들고 한번씩 탐색해가며 해당 번째의 알파벳 위치에 저장해 주었습니다. (ex: s[i]가 a라면 isChecked의 0번 위치에 1추가)

그 이후 이미 저장되 있는 값이라면 continue로 아니라면 그 알파벳 위치 이후부터 탐색 후 없다면 i를 return 해주었습니다.