LeetCode | Reverse Words in a String(C#)

题目:

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

 

代码:

        public static string reverseWords(string str)
        {
            string reverStr = "";
            int count = 0;
            Stack stack1 = new Stack();
            Stack stack2 = new Stack();
            foreach (var item in str)
            {
                if(item==' ')
                {
                    stack1.Push(item);
                    count = stack1.Count;
                    for (int i = 0; i < count; i++)
                    {
                        stack2.Push(stack1.Pop());
                    }
                }
                else
                {
                    stack1.Push(item);
                }
            }
            stack2.Push(' ');
            count = stack1.Count;
            for (int i = 0; i < count; i++)
            {
                stack2.Push(stack1.Pop());
            }
            count = stack2.Count - 1;
            for (int i = 0; i < count; i++)
            {
                reverStr = reverStr + stack2.Pop().ToString();
            }
            return reverStr;
        }

 

posted @ 2017-06-01 17:55  向萧  阅读(200)  评论(0编辑  收藏  举报