顛倒字符串中單詞的順序我有這個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
提交
取消
