为了账号安全,请及时绑定邮箱和手机立即绑定

颠倒字符串中单词的顺序

颠倒字符串中单词的顺序

颠倒字符串中单词的顺序我有这个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 关注
  • 779 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信