gpt4 book ai didi

java - 我的关于交换相邻字符的代码有什么问题?

转载 作者:行者123 更新时间:2023-12-02 10:26:54 25 4
gpt4 key购买 nike

问题:编写一个名为 swapPairs 的方法,该方法接受一个字符串作为参数,并返回该字符串,其中每对相邻字母都颠倒过来。如果字符串有奇数个字母,则最后一个字母不变。例如,调用 swapPairs("example") 应返回“xemalpe”,调用 swapPairs("hello there") 应返回“ehll ohtree”。

public static String swapPairs(String s) {
String t="";
if(s.length()%2==0) {
for (int i=0;i<s.length()/2;i++) {
t+=s.charAt(2*i+1)+s.charAt(2*i);
}
}
else {
for (int i=0;i<s.length()/2;i++) {
t+=s.charAt(2*i+1)+s.charAt(2*i);
}
t+=s.charAt(s.length()-1);
}
return t;
}

最佳答案

您只能使用 1 个循环,例如:

public static String swapPairs(String s) {
StringBuilder t = new StringBuilder();
for(int i = 0; i < s.length() - 1; i += 2) {
t.append(s.charAt(i + 1));
t.append(s.charAt(i));
}
if(s.length() % 2 == 1) { //appending the last character if needed
t.append(s.charAt(s.length() - 1));
}
return t.toString();
}

使用 StringBuilder 也是一个好主意:)

关于java - 我的关于交换相邻字符的代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53886368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com