反转字符串中单词的顺序

编程入门 行业动态 更新时间:2024-10-15 20:19:46
本文介绍了反转字符串中单词的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有这个字符串s1 =我的名字是XYZ,我想扭转单词的顺序,以便 s1 =ZYX是我的名字。

我可以使用额外的数组来做。我想很难,但是有可能做到这一点(不使用额外的数据结构),时间复杂度是O(n)?

解决方案

反转字符串,然后在第二遍中,反向每个单词...

在c#中,完全就地没有其他数组:

static char [] ReverseAllWords(char [] in_text) { int lindex = 0; int rindex = in_text.Length - 1; if(rindex> 1) { // reverse complete phrase in_text = ReverseString(in_text,0,rindex); //反转每个单词的结果反转短语 for(rindex = 0; rindex <= in_text.Length; rindex ++) { if(rindex = = in_text.Length || in_text [rindex] =='') { in_text = ReverseString(in_text,lindex,rindex - 1); lindex = rindex + 1; } } } return in_text; } static char [] ReverseString(char [] intext,int lindex,int rindex) { char tempc; while(lindex< rindex) { tempc = intext [lindex]; intext [lindex ++] = intext [rindex]; intext [rindex--] = tempc; } return intext; }

I have this string s1 = "My name is X Y Z" and I want to reverse the order of the words so that s1 = "Z Y X is name My".

I can do it using an additional array. I thought hard but is it possible to do it inplace (without using additional data structures) and with the time complexity being O(n)?

解决方案

reverse the string and then, in a second pass, reverse each word...

in c#, completely in-place without additional arrays:

static char[] ReverseAllWords(char[] in_text) { int lindex = 0; int rindex = in_text.Length - 1; if (rindex > 1) { //reverse complete phrase in_text = ReverseString(in_text, 0, rindex); //reverse each word in resultant reversed phrase for (rindex = 0; rindex <= in_text.Length; rindex++) { if (rindex == in_text.Length || in_text[rindex] == ' ') { in_text = ReverseString(in_text, lindex, rindex - 1); lindex = rindex + 1; } } } return in_text; } static char[] ReverseString(char[] intext, int lindex, int rindex) { char tempc; while (lindex < rindex) { tempc = intext[lindex]; intext[lindex++] = intext[rindex]; intext[rindex--] = tempc; } return intext; }

更多推荐

反转字符串中单词的顺序

本文发布于:2023-11-03 18:50:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555815.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   单词   顺序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!