Skip to content

Commit b611fb1

Browse files
easy string char loop
1957. Delete Characters to Make Fancy String Solved Easy Topics Companies Hint A fancy string is a string where no three consecutive characters are equal. Given a string s, delete the minimum possible number of characters from s to make it fancy. Return the final string after the deletion. It can be shown that the answer will always be unique. Example 1: Input: s = "leeetcode" Output: "leetcode" Explanation: Remove an 'e' from the first group of 'e's to create "leetcode". No three consecutive characters are equal, so return "leetcode". Example 2: Input: s = "aaabaaaa" Output: "aabaa" Explanation: Remove an 'a' from the first group of 'a's to create "aabaaaa". Remove two 'a's from the second group of 'a's to create "aabaa". No three consecutive characters are equal, so return "aabaa". Example 3: Input: s = "aab" Output: "aab" Explanation: No three consecutive characters are equal, so return "aab". Constraints: 1 <= s.length <= 105 s consists only of lowercase English letters. Seen this question in a real interview before? 1/5 Yes No Accepted 149.8K Submissions 208K Acceptance Rate 72.0% Topics String Companies Hint 1 What's the optimal way to delete characters if three or more consecutive characters are equal? Hint 2 If three or more consecutive characters are equal, keep two of them and delete the rest.
1 parent 2b0d30b commit b611fb1

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
public String makeFancyString(String s) {
3+
StringBuilder ans=new StringBuilder();
4+
int count=0;
5+
char prev=s.charAt(0);
6+
for(char curr:s.toCharArray()){
7+
if(curr==prev){
8+
count++;
9+
}
10+
else{
11+
count=1;
12+
}
13+
if(count<3){
14+
ans.append(curr);
15+
prev=curr;
16+
}
17+
}
18+
return ans.toString();
19+
}
20+
}

0 commit comments

Comments
 (0)