栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

反转句子的每个第二个单词

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

反转句子的每个第二个单词

您可以解决各种问题的简便方法!只需使用一个

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/410525.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号