我正在尝试反转每个句子的第二个单词
如果给定的字符串是:
My name is xyz
所需的输出应为:
My eman is zyx
我当前的输出是:
Ym eman s1 zyx
我无法达到所需的输出。不知道我在做什么错
这是我的代码
char[] sentence = " Hi my name is person!".toCharArray(); System.out.println(ReverseSentence(sentence)); } private static char[] ReverseSentence(char[] sentence) { //Given: "Hi my name is person!" //produce: "iH ym eman si !nosrep" if(sentence == null) return null; if(sentence.length == 1) return sentence; int startPosition=0; int counter = 0; int sentenceLength = sentence.length-1; //Solution handles any amount of spaces before, between words etc... while(counter <= sentenceLength) { if(sentence[counter] == ' ' && startPosition != -1 || sentenceLength == counter) //Have passed over a word so upon encountering a space or end of string reverse word { //swap from startPos to counter - 1 //set start position to -1 and increment counter int begin = startPosition; int end; if(sentenceLength == counter) { end = counter; } else end = counter -1; char tmp; //Reverse characters while(end >= begin){ tmp = sentence[begin]; sentence[begin] = sentence[end]; sentence[end] = tmp; end--; begin++; } startPosition = -1; //flag used to indicate we have no encountered a character of a string } else if(sentence[counter] !=' ' && startPosition == -1) //first time you encounter a letter in a word set the start position { startPosition = counter; } counter++; } return sentence; }
您可以解决各种问题的简便方法!只需使用一个flag将指示 偶数 或 奇数 位置的变量,更准确地说是任何单词都将被反转!
flag
查看我在您的代码中进行的以下修改,仅添加了三行:
private static boolean flag = true;// added a variable flag to check if we reverse the word or not. private static char[] ReverseSentence(char[] sentence) { //Given: "Hi my name is person!" //produce: "iH ym eman si !nosrep" if(sentence == null) return null; if(sentence.length == 1) return sentence; int startPosition=0; int counter = 0; int sentenceLength = sentence.length-1; //Solution handles any amount of spaces before, between words etc... while(counter <= sentenceLength) { if(sentence[counter] == ' ' && startPosition != -1 || sentenceLength == counter) //Have passed over a word so upon encountering a space or end of string reverse word { flag = !flag; // first time (odd position) we are not going to reverse! //swap from startPos to counter - 1 //set start position to -1 and increment counter int begin = startPosition; int end; if(sentenceLength == counter) { end = counter; } else end = counter -1; char tmp; //Reverse characters while(end >= begin & flag){ //lets see whether we are going to reverse or not tmp = sentence[begin]; sentence[begin] = sentence[end]; sentence[end] = tmp; end--; begin++; } startPosition = -1; //flag used to indicate we have no encountered a character of a string } else if(sentence[counter] !=' ' && startPosition == -1) //first time you encounter a letter in a word set the start position { startPosition = counter; } counter++; } return sentence; }
输入项
我叫xyz
输出:
我的eman是zyx