这是问题的声明:如何解决Codingbat String-2的挑战?
给定一个字符串,通过移动的第一个字符来接下来的两个字符后,计算新的字符串,所以“ABC”产量“BCA”。对每个后续3个字符组重复此过程,因此“abcdef”会产生“bcaefd”。最后忽略任何少于3个字符的组。
这里是我的代码:
// oneTwo("abc") → "bca"
// oneTwo("tca") → "cat"
// oneTwo("tcagdo") → "catdog"
public String oneTwo(String str) {
String x = "";
if (str.length() < 3) {
return "";
// return empty
} else if (str.length() == 3) {
String s = str.substring(1, str.length());
x = s + str.substring(0, 1); // last two + first char
} else if (str.length() > 3) {
int third = 2;
// start with the third element index of 2
for (int i = 0; i < str.length(); i++) {
if (i == third) {
// given three chars substring first char
// substring last two chars and add that to x
x += (str.substring(third - 1, third + 1) +
str.substring(third - 2, third - 2 + 1));
third += 3;
//work with this line but why??????
}
//third +=3;
// doesn't work with this line but why???????
}// end of for loop
}
return x;
// return modified string x
}
随着third +=3
if语句,在里面工作,但是当我把if语句的那个之外我没有得到期望的输出。我不明白为什么?
你的问题已经进行了分析。我建议你消耗你的输入字符串,而不是遍历字符。这将使您可以始终只查看前三个字符。这样,你所做的所有指标数学(并且从现在开始的三周内将无法轻松理解):)将会消失。 – thst