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\"
If a regex based solution is acceptable you can do:
str = str.replaceAll("(.)\\1+","$1");
Ideone Link
I would do it like this:
public static String stringClean(String str) {
if (str == null || "".equals(str))
return str;
StringBuffer buffer = new StringBuffer();
char[] chars = str.toCharArray();
buffer.append(chars[0]);
for (int i = 1; i < chars.length; i++) {
if (chars[i] != chars[i-1])
buffer.append(chars[i]);
}
return buffer.toString();
}
function cleanString(toClean){
return toClean.replace(/(\S)\1(\1)*/g,"$1")
}
Demo in jsFiddle
If you aren't restricted to use collections from java.util
I recommend to use Set
. See example below.
public static String stringClean(String input) {
Set<Character> result = new LinkedHashSet<Character>();
for (char c : input.toCharArray()) {
result.add(c);
}
StringBuilder sb = new StringBuilder();
for (char c : result)
sb.append(c);
return sb.toString();
}
Looks like you are solving codingbat problems, it is good,
I m a beginner too. This exercise is supposed to be just using recursion
This is my solution:
public String stringClean(String str) {
if (str.length() <= 1)
return str;
String adj1 = str.substring(0,1);
String adj2 = str.substring(1,2);
String rest = str.substring(1);
if (adj1.equals(adj2)) {
return stringClean(rest);
} else
return adj1 + stringClean(rest);
}
Hope it helps
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.
if(adjacentPosition != str.length()){
adjacentChar = str.charAt(adjacentPosition);
System.out.println("adjacentChar ::" + adjacentChar);
}
else {
adjacentChar = '/u0000';
}
EDIT
I think that the second issue you have mentioned is in this piece of code
if(sb.toString().indexOf(startChar) != -1){
sb.append(adjacentChar);
System.out.println("Appended String in if part-->"
+ sb.toString());
}
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.