Skip to content

Create DeleteCharacterstoMakeFancyString.java #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 1, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions Leetcode/DeleteCharacterstoMakeFancyString.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
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.
**/
class Solution {
public String makeFancyString(String s) {

if(s==null || s.length()<3) return s;
int count=1;
StringBuffer sb = new StringBuffer();
char lastchar = s.charAt(0);
sb.append(lastchar);
for(int i=1;i<s.length();i++){

if(s.charAt(i)==lastchar){
if(count<2){
sb.append(s.charAt(i));
}
count++;
}
else{
count=1;
sb.append(s.charAt(i));
lastchar = s.charAt(i);
}
}

return sb.toString();
}
}

// best soltion
class Solution {
public String makeFancyString(String s) {
int sameCount = 0;
StringBuilder sb = new StringBuilder();
char prev = s.charAt(0);
for (char cur : s.toCharArray()) {
if (cur == prev) {
sameCount++;
}
else {
sameCount = 1;
}
if (sameCount < 3) sb.append(cur);
prev = cur;
}
return sb.toString();
}
}
Loading