Problem:
Suppose the string "yak" is unlucky. Given a string, return a version where all the "yak" are removed, but the "a" can be any char. The "yak" strings will not overlap.
stringYak("yakpak") → "pak"
stringYak("pakyak") → "pak"
stringYak("yak123ya") → "123ya"
Solution:
public String stringYak(String str) { String result = ""; for (int i=0; i<str.length(); i++) { if (i+2<str.length() && str.charAt(i)=='y' && str.charAt(i+2)=='k') { i = i + 2; } else { result = result + str.charAt(i); } } return result; }
public String stringYak(String str) {
ReplyDeleteif(str.contains("yak")){
return str.replace("yak","");
}
return str;
}
This is the beauty way you have return it. I am a beginner and I understood it clearly how to think and write in shortcut.
DeleteWrong code. The a can be anything.
Deleteyes but the requirement says the middle char , 'a', can be any character so your solution is one dimensional.
DeleteEasiest way:
ReplyDeletepublic String stringYak(String str) {
return str.replaceAll("y.k", ""); // The dot (.) means ‘any char’
}
Thank you! It's cool idea!
DeleteString [] b=str.split("yak");
ReplyDeletefor (String s:b
) {
System.out.println(s);
}
use in intidea
public String stringYak(String str) {
DeleteString res="";
String[] sb = str.split("yak");
for(String s: sb){
res = res+s;
}
return res;
}