문제: leetcode.com/problems/bulls-and-cows/
문자열 중 같은 position에 있으면 A, 아니면 자리는 같지 않더라도 같은 값이 다른 포지션에 있을 경우 B다.
class Solution {
public:
string getHint(string secret, string guess) {
unordered_map<char, int> m;
int A = 0;
int B = 0;
for(int i = 0; i < secret.size(); i++){
if(secret[i] == guess[i]){
A++;
secret[i] = ' ';
guess[i] = ' ';
} else {
m[secret[i]]++;
}
}
for(int i = 0; i < guess.size(); i++){
char c = guess[i];
if(guess[i] == ' ') continue;
if(m[c] > 0){
m[c] -= 1;
B++;
}
}
string ret = to_string(A) + "A" + to_string(B) + "B";
return ret;
}
};

'* Computer Science > Algorithm' 카테고리의 다른 글
| 300. Longest Increasing Subsequence (0) | 2021.03.08 |
|---|---|
| 135. Candy (0) | 2021.02.20 |
| 642. Design Search Autocomplete System (0) | 2021.02.13 |
| 380. Insert Delete GetRandom O(1) (0) | 2021.02.11 |
| 297. Serialize and Deserialize Binary Tree (0) | 2021.02.09 |