Problem:
Given a string, return a version where all the "x" have been removed. Except an "x" at the very start or end should not be removed.
stringX("xxHxix") → "xHix"
stringX("abxxxcd") → "abcd"
stringX("xabxxxcdx") → "xabcdx"
Solution:
public String stringX(String str) { String result = ""; int len = str.length(); for (int i = 0; i < len; i++){ char temp = str.charAt(i); if (!(i > 0 && i < len - 1 && temp == 'x')) result = result + temp; } return result; }
public String stringX(String str) {
ReplyDeleteif (str.length()<=2) return str;
char start= str.charAt(0) ;
char end= str.charAt(str.length()-1);
str = str.substring(1,str.length()-1).replace("x", "");
return start + str + end;
}
Good solution!
DeleteThis is the best solution:
ReplyDeletepublic String stringX(String str) {
int len = str.length();
if(str.length()<=2){
return str;
}
if(str.startsWith("x") && str.endsWith("x")){
String mid = str.substring(1,len-1);
return "x" + mid.replaceAll("x", "") + "x";
} else if(str.startsWith("x") && !str.endsWith("x")){
String start = str.substring(1,len);
return "x" + start.replaceAll("x", "");
} else if(str.endsWith("x") && !str.startsWith("x")){
String end = str.substring(0,len-1);
return end.replaceAll("x", "") + "x";
} else {
return str.replaceAll("x", "");
}
}
With Regex
ReplyDeletepublic String stringX(String str) {
return str.replaceAll("\\B[x]\\B", "");
}