알고리즘
Delete Characters to Make Fancy String
짬뽕얼큰하게
2025. 2. 20. 08:40
Leetcode Problem:
Summary
- The problem is to delete the minimum possible number of characters from a string to make it a fancy string, where no three consecutive characters are equal.
Approach
- The approach used is to iterate through the string and check for consecutive characters
- If three consecutive characters are equal, they are skipped
- Otherwise, they are added to the result string.
Complexity
- O(n), where n is the length of the string
Explanation
- The solution code initializes a string `ss` with the first character of the input string
- It then iterates through the rest of the string, checking for consecutive characters
- If three consecutive characters are equal, they are skipped
- Otherwise, they are added to the result string
- The code also keeps track of the count of consecutive characters and resets it when a different character is encountered.
Solution Code:
class Solution {
public:
string makeFancyString(string s) {
string ss = string(1,s[0]);
int repeat_cnt = 1;
char before_char = s[0];
for(int i = 1 ; i < s.size(); i++){
if (before_char == s[i]){
repeat_cnt++;
if(repeat_cnt >= 3) continue;
} else {
repeat_cnt = 1;
}
ss += s[i];
before_char = s[i];
}
return ss;
}
};
class Solution {
public:
string makeFancyString(string s) {
string ss = string(1,s[0]);
int repeat_cnt = 1;
char before_char = s[0];
for(int i = 1 ; i < s.size(); i++){
if (before_char == s[i]){
repeat_cnt++;
if(repeat_cnt >= 3) continue;
} else {
repeat_cnt = 1;
}
ss += s[i];
before_char = s[i];
}
return ss;
}
};