There is a problem in codingbat.com which you're supposed to remove "yak" substring from the original string. and they provided a solution for that which I can't understand what happens when the if statement goes true!
public String stringYak(String str) {
String result = "";
for (int i=0; i<str.length(); i++) {
// Look for i starting a "yak" -- advance i in that case
if (i+2<str.length() && str.charAt(i)=='y' && str.charAt(i+2)=='k') {
i = i + 2;
} else { // Otherwise do the normal append
result = result + str.charAt(i);
}
}
return result;
}
It just adds up i by 2 and what? When it appends to the result string?
Link of the problem: https://codingbat.com/prob/p126212
The provided solution checks for all single characters in the input string. For this i
is the current index of the checked character. When the current char is not a y
and also the (i+2)
character is not a k
the current char index is advanced by 1 position.
Example:
yakpak
012345
i
So here in the first iteration the char at i
is y
and i+2
is a k
, so we have to skip 3 chars. Keep in mind i
is advanced by 1 everytime. So i has to be increased by 2 more. After this iteration i
is here
yakpak
012345
i
So now the current char is no y
and this char will get added to the result string.
But it's even simpler in Java as this functionality is build in with regex:
public String stringYak(String str) {
return str.replaceAll("y.k","");
}
The .
means every char.
If i
is pointing at a y
and there is as k
two positions down, then it wants to skip the full y*k
substring, so it add 2
to i
so i
now refers to the k
. WHen then loop continues, i++
will skip past the k
, so in effect, the entire 3-letter y*k
substring has been skipped.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.