zoukankan      html  css  js  c++  java
  • [LC] 151. Reverse Words in a String

    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.

    Solution 1:
    class Solution {
        public String reverseWords(String s) {
            if (s == null || s.length() == 0) {
                return "";
            }
            char[] charArr = s.toCharArray();
            swap(charArr, 0, s.length() - 1);
            int i = 0, start = 0;
            while (i < s.length()) {
                if (i == 0 || charArr[i - 1] == ' ') {
                    start = i;
                }
                
                if (i == charArr.length - 1 || charArr[i + 1] == ' ') {
                    swap(charArr, start, i);
                }
                i += 1;
            }
            
            // need to trim space inside
            int slow = 0;
            for (int j = 0; j < charArr.length; j++) {
                if (charArr[j] == ' ' && (j == 0 || charArr[j - 1] == ' ')) {
                    continue;
                }
                charArr[slow++] = charArr[j];
            }
            return new String(charArr, 0, slow).trim();
        }
        
        private void swap(char[] charArr, int i, int j) {
            while (i < j) {
                char tmp = charArr[i];
                charArr[i] = charArr[j];
                charArr[j] = tmp;
                i += 1;
                j -= 1;
            }
        }
    }

    Solution 2:

    class Solution {
        public String reverseWords(String s) {
            if (s == null || s.length() == 0) {
                return "";
            }
            String[] strArr = s.split("\s+");
            StringBuilder sb = new StringBuilder();
            for (int i = strArr.length - 1; i >= 0; i--) {
                sb.append(strArr[i] + " ");
            }
            return sb.toString().trim();
        }
    }
  • 相关阅读:
    Jenkins安装
    Python操作yaml文件
    class 中构造函数与析构函数
    python发送邮件(yagmail模块)
    filter、map函数的区别
    python redis操作
    多个 python的pip版本选择
    python Excel操作
    python MD5操作
    缓存淘汰算法之LRU实现
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12296922.html
Copyright © 2011-2022 走看看