public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "Let's take LeetCode contest";
reverseWords(str);
}
private static void reverseWords(String str) {
// TODO Auto-generated method stub
String[] words = str.split("\\s");
String reverse = "";
String word="";
ArrayList<String> al = new ArrayList<String>();
for(int i=0 ; i < words.length;i++){
al.add(words[i]);
for(int j=al.get(i).length()-1;j>=0;j--){
reverse=reverse+al.get(i).charAt(j);
word= reverse.replaceAll("..", "$0 ");
}
}
System.out.println(str);
System.out.println(word);
}
此代码放弃了:“s'teLekatedoCteeLtsetnoc”
但预期的结果应该是:“s'teL ekat edoCteeL tsetnoc”
答案 0 :(得分:4)
实际上,发布的代码不会产生您声明的输出;它输出"s' te Le ka te do Ct ee Lt se tn oc"
。你是(出于某种原因)一次颠倒一对字母。
有时,最好的方法是尽可能简单地编写代码。以下是如何在一个(IMHO可读)行中执行此操作:
private static void reverseWords(String str) {
System.out.println(
Arrays.stream(str.split(" ")) // split into words
.map(StringBuilder::new) // use a StringBuilder for each word
.map(StringBuilder::reverse) // reverse each word
.collect(Collectors.joining(" "))); // join em back up with spaces
}
答案 1 :(得分:0)
private static void reverseWords(String str) {
// TODO Auto-generated method stub
String[] words = str.split("\\s");
String reverse = "";
int len = words.length;
for(int i=0;i<len;i++){
reverse = reverse+new StringBuilder(words[i]).reverse().toString();
if(i<len-1){
reverse = reverse+" ";
}
}
System.out.println(str);
System.out.println(reverse);
}
尝试将此作为你的reverseWords()方法。
答案 2 :(得分:0)
public class Reverse {
public static void main(String[] args) {
String str = "Let's take LeetCode contest";
reverseWords(str);
}
private static void reverseWords(String str) {
char[] charArray = str.toCharArray();
boolean flag = false;
int start = 0;
int end = 0;
for (int i = 0; i < str.length(); i++) {
if (charArray[i] == ' ' && !flag) {
flag = true;
end = i - 1;
reverseWord(charArray, start, end);
}
if (charArray[i] != ' ' && flag) {
start = i;
flag = false;
}
}
reverseWord(charArray, start, charArray.length - 1);
System.out.println(str);
System.out.println(String.valueOf(charArray));
}
private static void reverseWord(char[] ch, int i, int j) {
while (i < j) {
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
i++;
j--;
}
}
}