알고리즘/LeetCode
[LeetCode/easy/String] First Unique Character in a String
녕이
2022. 9. 20. 11:27
728x90
https://leetcode.com/problems/first-unique-character-in-a-string/
First Unique Character in a String - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문자열 s가 주어졌을 때, s 내의 첫 번째 non-repeating 문자를 찾고 그것의 index 반환하기. 없으면 return -1
string의 find()함수는 find() 함수[#include algorithm]와 다른데, 이 함수는 찾고 싶은 위치를 정할 수 있다는 것이다!
int firstUniqChar(string s) {
int answer = -1;
for(char c = 'a'; c <= 'z'; c++){
size_t i = s.find(c);
if(i == string::npos) continue; //이 알파벳은 문자열에 없음
if(s.find(c, i+1) == string::npos){ //이 알파벳 다음부터 찾아보기 string::npos라면 없는 것!
if(i < answer || answer == -1) answer = i;
}
}
return answer;
}
728x90