[算法] C# Revert 单词反转字符串[低时间复杂度]

时间:2014-05-13 08:32:48   收藏:0   阅读:213
无聊期间想起了一道字符串反转的问题。 大致要求输入“I am a good boy”,输出"boy good a am I"。 要求不能用已经封装好的方法实现。于是乎,我上网查了一下,基本都是用了封装后类库。于是我自己写了一个小算法,低时间复杂度高空间复杂度的算法。

        private string Revert(string str)
        {
            if (str.Length == 0)
            {
                return string.Empty;
            }
            string newStr = null;
            int indexFirst = -1;
            int indexLast = str.Length - 1;
            for (int i = str.Length - 1; i >= 0; i--)
            {
                if (str[i] == ‘ ‘)
                {
                    indexFirst = i + 1;
                    while (indexLast - indexFirst >= 0)
                    {
                        newStr += str[indexFirst];
                        ++indexFirst;
                    }
                    newStr = newStr + ‘ ‘;
                    indexLast = i - 1;
                    indexFirst = -1;
                }
                if (i == 0)
                {
                    indexFirst = i;
                    while (indexLast - indexFirst >= 0)
                    {
                        newStr += str[indexFirst];
                        ++indexFirst;
                    }
                }

            }
            return newStr;
        }




[算法] C# Revert 单词反转字符串[低时间复杂度],布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!