颠倒字符串中单词的顺序我有这个string s1 = "My name is X Y Z"我想把单词的顺序颠倒一下s1 = "Z Y X is name My".我可以使用一个额外的数组来完成它。我想了很难,但是否有可能在不使用额外数据结构的情况下,在时间复杂度为O(N)的情况下,在内部完成此操作?
3 回答
跃然一笑
TA贡献1826条经验 获得超6个赞
s1 = "Z Y X si eman yM"
s1 = "Z Y X is name My"
墨色风雨
TA贡献1853条经验 获得超6个赞
扭转字符串,然后,在第二次,反转每个单词.。
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;}
波斯汪
TA贡献1811条经验 获得超4个赞
Not exactly in place, but anyway: Python: >>> a = "These pretzels are making me thirsty" >>> " ".join(a.split()[::-1]) 'thirsty me making are pretzels These'
添加回答
举报
0/150
提交
取消