Given a string made up of letters a, b, and/or c, switch the position of letters a and b (change a to b and vice versa). Leave any incidence of c untouched.
Example:
'acb' --> 'bca'
'aabacbaa' --> 'bbabcabb'
我的代碼->
public class Switch {
public static String switcheroo(String x) {
char[] arr = x.toCharArray();
for (int i=0;i<(x.length()-1);i ){
if(arr[i]=='a'){
arr[i]='b';
}
else if(arr[i]=='b'){
arr[i]='a';
}
}
x = String.valueOf(arr);
return x;
}
}
我收到一個錯誤
expected:<aaabcccbaa[a]> but was:<aaabcccbaa[b]>
我無法弄清楚這一點,請幫忙。鏈接到問題 - https://www.codewars.com/kata/57f759bb664021a30300007d/train/java
uj5u.com熱心網友回復:
問題出在你的回圈上,當從零開始迭代時,只檢查小于 length i < x.lenth()。以一開頭時需要“長度減一”,例如:for (int i = 1; i < (x.length() - 1); i ) .... 由于您同時執行了最后一個字符,因此永遠不會迭代并且不能被回圈內的代碼更改。
for (int i = 0; i < x.length(); i ) {
if (arr[i] == 'a') {
arr[i] = 'b';
}
else if (arr[i] == 'b') {
arr[i] = 'a';
}
}
uj5u.com熱心網友回復:
看來您的問題來自您的索引,您在陣列上回圈,但您的代碼停在i < (x.length -1). 要修復它,您只需洗掉減一部分:i < x.length或i <= (x.length - 1)
uj5u.com熱心網友回復:
您可以使用以下代碼:
#include <string>
#include <algorithm>
#include <iterator>
std::string switcheroo(const std::string &s) {
std::string tmp;
std::transform(s.begin(), s.end(), std::back_inserter(tmp),
[](const auto& i) {
if (i == 'a') { return 'b'; }
if (i == 'b') { return 'a'; }
return i;
});
return tmp;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/460322.html
標籤:爪哇
