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;
}
};
'알고리즘' 카테고리의 다른 글
String Compression III (0) | 2025.02.20 |
---|---|
Rotate String (0) | 2025.02.20 |
Minimum Total Distance Traveled (0) | 2025.02.20 |
The k-th Lexicographical String of All Happy Strings of Length n (0) | 2025.02.19 |
Minimum Number of Removals to Make Mountain Array (0) | 2025.02.19 |