151. Reverse Words in a String

Description

Given an input string, reverse the string word by word.
For example,Given s = "the sky is blue
",return "blue is sky the
".
**Update (2015-02-12):
**For C programmers: Try to solve it in-place in O(1) space.
click to show clarification.
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.

Solution

Two pointers

思路还是很清晰的,先翻转每个word,再翻转整个String。
有坑的地方是:

  1. 开头和结尾的space要移除掉。
  2. word之间要保留一个space。这个可以边遍历边对words进行计数,遇到新单词且之前已经有单词才插入space。
public class Solution {
    public static void main(String[] args) {
        final String input = "  ab c dec   ";
        System.out.println("[" + new Solution().reverseWords(input) + "]");
    }

    public String reverseWords(String s) {
        if (s == null || s.isEmpty()) {
            return s;
        }
        char[] chars = s.toCharArray();
        int len = compressWords(chars);
        reverseStr(chars, 0, len - 1);
        return String.valueOf(chars, 0, len);
    }

    public int compressWords(char[] chars) {
        int i = 0;
        int j = 0;
        int wordsCount = 0;

        while (i < chars.length) {
            // escape spaces and find the beginning of a new word
            while (i < chars.length && chars[i] == ' ') {
                ++i;
            }
            if (i == chars.length) break;
            if (wordsCount > 0) {
                chars[j++] = ' ';   // leave a space in between of words
            }
            int k = j;
            // find the ending of the word
            while (i < chars.length && chars[i] != ' ') {
                chars[j++] = chars[i++];
            }
            reverseStr(chars, k, j - 1);
            ++wordsCount;
        }

        return (j > 0 && chars[j - 1] == ' ') ? j - 1 : j; // remove the trailing space if any
    }

    public void reverseStr(char[] chars, int start, int end) {
        while (start < end) {
            char tmp = chars[start];
            chars[start++] = chars[end];
            chars[end--] = tmp;
        }
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容