反转字符串中单词的顺序 [英] Reverse the ordering of words in a string

查看:178
本文介绍了反转字符串中单词的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个字符串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;
}

这篇关于反转字符串中单词的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆