Skip to content

Commit 46123f3

Browse files
Create DeleteCharacterstoMakeFancyString.java
1 parent 39dfb72 commit 46123f3

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
1957. Delete Characters to Make Fancy String
3+
Solved
4+
Easy
5+
Topics
6+
Companies
7+
Hint
8+
A fancy string is a string where no three consecutive characters are equal.
9+
10+
Given a string s, delete the minimum possible number of characters from s to make it fancy.
11+
12+
Return the final string after the deletion. It can be shown that the answer will always be unique.
13+
**/
14+
class Solution {
15+
public String makeFancyString(String s) {
16+
17+
if(s==null || s.length()<3) return s;
18+
int count=1;
19+
StringBuffer sb = new StringBuffer();
20+
char lastchar = s.charAt(0);
21+
sb.append(lastchar);
22+
for(int i=1;i<s.length();i++){
23+
24+
if(s.charAt(i)==lastchar){
25+
if(count<2){
26+
sb.append(s.charAt(i));
27+
}
28+
count++;
29+
}
30+
else{
31+
count=1;
32+
sb.append(s.charAt(i));
33+
lastchar = s.charAt(i);
34+
}
35+
}
36+
37+
return sb.toString();
38+
}
39+
}
40+
41+
// best soltion
42+
class Solution {
43+
public String makeFancyString(String s) {
44+
int sameCount = 0;
45+
StringBuilder sb = new StringBuilder();
46+
char prev = s.charAt(0);
47+
for (char cur : s.toCharArray()) {
48+
if (cur == prev) {
49+
sameCount++;
50+
}
51+
else {
52+
sameCount = 1;
53+
}
54+
if (sameCount < 3) sb.append(cur);
55+
prev = cur;
56+
}
57+
return sb.toString();
58+
}
59+
}

0 commit comments

Comments
 (0)