LeetCode 151. Reverse Words in a String (Java版; Medium)

welcome to my blog

LeetCode 151. Reverse Words in a String (Java版; Medium)

题目描述

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

 

Example 1:

Input: "the sky is blue"
Output: "blue is sky the"
Example 2:

Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:

Input: "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
 

Note:

A word is defined as a sequence of non-space characters.
Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
You need to reduce multiple spaces between two words to a single space in the reversed string.
 

Follow up:

For C programmers, try to solve it in-place in O(1) extra space.

第一次做; 从后往前, 注意单独处理开头

class Solution {
    public String reverseWords(String s) {
        StringBuilder sb = new StringBuilder();
        s = s.trim();
        int n=s.length(), i=n-1, j=n;
        while(i>=0){
            if(s.charAt(i)==' '){
                sb.append(s.substring(i+1,j)).append(" ");
                while(s.charAt(i)==' ')
                    i--;
                j=i+1;
            }
            else
                i--;
        }
        //单独处理开头
        sb.append(s.substring(0,j));
        return sb.toString();
    }
}

第一次做; 逐个字符逐个字符扫描, 碰到非空字符就取出以该字符开始的单词, 配合; 从前往后, 还可以从后往前, 这样就不用tmp这个StringBuilder了

class Solution {
    public String reverseWords(String s) {
        StringBuilder sb = new StringBuilder();
        int l = 0;
        while(l<s.length()){
            char ch = s.charAt(l);
            if(ch==' '){
                l++;
                continue;
            }
            StringBuilder tmp = new StringBuilder();
            int r = l+1;
            tmp.append(ch);
            while(r<s.length() && s.charAt(r)!=' '){
                tmp.append(s.charAt(r));
                r++;
            }
            tmp.append(" ");
            sb.insert(0, tmp.toString());
            l = r+1;
        }
        return sb.toString().trim();
    }
}

LeetCode优秀题解

https://leetcode.com/problems/reverse-words-in-a-string/discuss/47720/Clean-Java-two-pointers-solution-(no-trim(-)-no-split(-)-no-StringBuilder)

public class Solution {
  
  public String reverseWords(String s) {
    if (s == null) return null;
    
    char[] a = s.toCharArray();
    int n = a.length;
    
    // step 1. reverse the whole string
    reverse(a, 0, n - 1);
    // step 2. reverse each word
    reverseWords(a, n);
    // step 3. clean up spaces
    return cleanSpaces(a, n);
  }
  
  void reverseWords(char[] a, int n) {
    int i = 0, j = 0;
      
    while (i < n) {
      while (i < j || i < n && a[i] == ' ') i++; // skip spaces
      while (j < i || j < n && a[j] != ' ') j++; // skip non spaces
      reverse(a, i, j - 1);                      // reverse the word
    }
  }
  
  // trim leading, trailing and multiple spaces
  String cleanSpaces(char[] a, int n) {
    int i = 0, j = 0;
      
    while (j < n) {
      while (j < n && a[j] == ' ') j++;             // skip spaces
      while (j < n && a[j] != ' ') a[i++] = a[j++]; // keep non spaces
      while (j < n && a[j] == ' ') j++;             // skip spaces
      if (j < n) a[i++] = ' ';                      // keep only one space
    }
  
    return new String(a).substring(0, i);
  }
  
  // reverse a[] from a[i] to a[j]
  private void reverse(char[] a, int i, int j) {
    while (i < j) {
      char t = a[i];
      a[i++] = a[j];
      a[j--] = t;
    }
  }
  
}
发布了580 篇原创文章 · 获赞 130 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/littlehaes/article/details/104230014