亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

顛倒字符串中單詞的順序

顛倒字符串中單詞的順序

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


查看完整回答
反對 回復 2019-07-04
?
墨色風雨

TA貢獻1853條經驗 獲得超6個贊

扭轉字符串,然后,在第二次,反轉每個單詞.。

在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);

        //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;}


查看完整回答
反對 回復 2019-07-04
?
波斯汪

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'


查看完整回答
反對 回復 2019-07-04
  • 3 回答
  • 0 關注
  • 851 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號