i have the following problem
Given a string, return a “cleaned” string where adjacent chars that are the same have been reduced to a single char. So "yyzzza" yields "yza".
stringClean("yyzzza") → "yza"
stringClean("abbbcdd") → "abcd"
stringClean("Hello") → "Helo"
Im trying my code for the input stringClean("abbbcdd") → "abcd"
My code is below.Im getting the partial appended string after doing the adjacent character comparison hence as of now im getting appended stringBuilder "sb=abc" which is not the correct output i should get the output as "abcd",
class cleanString{
public static String stringClean(String str){
int startIndex = str.indexOf(str);
char startChar = '\u0000';
char adjacentChar = '\u0000';
System.out.println("startIndex-->" + startIndex);
final StringBuilder sb = new StringBuilder();
for(startIndex = 0; startIndex < str.length(); startIndex += 1){
startChar = str.charAt(startIndex);
System.out.println("startIndex ::" + startIndex);
System.out.println("startChar ::" + startChar);
final int adjacentPosition = startIndex + 1;
System.out.println("adjacentPosition ::" + adjacentPosition);
if(adjacentPosition != str.length()){
adjacentChar = str.charAt(adjacentPosition);
System.out.println("adjacentChar ::" + adjacentChar);
}
if(startChar == adjacentChar){
System.out.println("startChar ::" + startChar);
System.out.println("adjacentChar::" + adjacentChar);
System.out.println("Before Substring string --->" + str);
str = str.substring(1);
startIndex--;
System.out.println("After Substring string --->" + str);
System.out.println("IndexOf check ---->"
+ sb.toString().indexOf(startChar));
if(sb.toString().indexOf(startChar) != -1){
sb.append(adjacentChar);
System.out.println("Appended String in if part-->"
+ sb.toString());
}
} else{
str = str.substring(1);
startIndex--;
sb.append(startChar);
System.out.println("Appended String --->" + sb.toString());
}
}// end of for loop
return sb.toString();
}
//im getting output as abc...which is partial appended string
public static void main(String ...args){
String outputCleanString=new cleanString().stringClean("abbbcdd");
System.out.println("Cleaned String --->"+outputCleanString);
}
}
*Observation:*after i get the appended string “abc”,and then when i move to compare the final set of characters “dd” im facing the problem in that part.
For your code and the specific issue you have mentioned if the adjacent position is beyond the bounds of your string set adjacentChar to the null char as otherwise adjacentChar is seen as the last character in the string, which means that an append is not done.
EDIT
I think that the second issue you have mentioned is in this piece of code
As e and o are in the buffer from Hello they are being appended when Bookkeeper is being checked. I don’t think you need that line so remove it and that should fix Hello Bookkeeper.
Although Mohoamed’s answer will also work.