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();
        }
    }
  • 相关阅读:
    vue2 下载scss依赖包
    fastjson使用
    vscode format
    flutter 中涉的深拷贝
    通过pom给maven添加编译插件
    IDEA添加动态模板(Live Templates)
    Maven启动tomcat:run异常
    Redis
    tomcat启动时启动窗口出现乱码的解决方案
    无效的源发行版,解决方案
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12296922.html
Copyright © 2011-2022 走看看