這是問題的聲明:如何解決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