PS/LeetCode
[LeetCode] May Challenge 5 - First Unique Character in a String
판교토끼
2020. 5. 5. 17:47
728x90
4일차 문제를 푼 줄 알았는데 착오로 풀지 않고 넘어가버렸다 ㅠㅠ
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
문자열에서 한 번만 등장하는 최초의 문자를 찾으면 된다. 문자 별 기본은 -1, 2회 이상 등장은 -2, 1회 등장은 index로 한 후에 최소값을 반환하였다.
class Solution {
public:
int firstUniqChar(string s) {
vector<int> counts(26,-1);
int result=2147483647;
for(int i=0;i<s.size();i++) {
if(counts[s[i]-'a']==-1)
counts[s[i]-'a']=i;
else
counts[s[i]-'a']=-2;
}
for(int i=0;i<26;i++) {
if(counts[i]>=0 && counts[i]<result)
result=counts[i];
}
if(result==2147483647)
return -1;
return result;
}
};
728x90