码迷,mamicode.com
首页 > 其他好文 > 详细

[lintcode 2 easy Reverse Words in a String]

时间:2015-11-07 06:31:07      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

Problem

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

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

 
Clarification

What constitutes a word?
A sequence of non-space characters constitutes a word.

Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces

How about multiple spaces between two words?
Reduce them to a single space in the reversed string

这题在不考虑multi space空格的情况下的思路:将string全部反转,然后将反转后的string words by words反转。  两次反转,in place操作。

如果考虑multi space,必须改变String,因为String对象本身是不可以改变的,所以要用StringBuilder来处理

思路:设置指针指向单词的最后一位,

另一个指针从字符串最后一位向前遍历,碰到空格,则将该单词向后遍历挨个添加至新string中。

 

public class Solution {
    /**
     * @param s : A string
     * @return : A string
     */
    public String reverseWords(String s) {
        // write your code
       StringBuilder sb = new StringBuilder();
            int end = s.length();
            for (int i = s.length()-1; i >= -1; i--)
            {
                if (i == -1 || s.charAt(i) == ‘ ‘ )
                {
                    if (i + 1 < end)
                    {
                        if (sb.length() > 0)
                            sb.append(" ");
                        for (int j = i + 1; j < end; j++)
                        {
                            sb.append(s.charAt(j));
                        }
                    }
                    end = i;
                }
            }
            return sb.toString();

      }
}

 

[lintcode 2 easy Reverse Words in a String]

标签:

原文地址:http://www.cnblogs.com/kittyamin/p/4944160.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!