zoukankan      html  css  js  c++  java
  • 557. Reverse Words in a String III

    Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

    Example 1:

    Input: "Let's take LeetCode contest"
    Output: "s'teL ekat edoCteeL tsetnoc"
    

    Note: In the string, each word is separated by single space and there will not be any extra space in the string.

    time: O(n), space: O(1)

    class Solution {
        public String reverseWords(String s) {
            String[] strs = s.split(" ");
            StringBuilder sb = new StringBuilder();
            for(String str : strs) {
                StringBuilder tmp = new StringBuilder(str);
                sb.append(tmp.reverse().append(" "));
            }
            return sb.toString().trim();
        }
    }

    faster, time: O(n), space: O(1)

    class Solution {
        public String reverseWords(String s) {
            char[] str = s.toCharArray();
            int i = 0, j = 0;
            while(j < str.length) {
                if(str[j] == ' ') {
                    reverse(str, i, j - 1);
                    j++;
                    i = j;
                } else {
                    j++;
                }
            }
            reverse(str, i, j - 1);     // last word
            return new String(str);
        }
        
        private void reverse(char[] c, int i, int j) {
            while(i < j) {
                char tmp = c[i];
                c[i] = c[j];
                c[j] = tmp;
                i++;
                j--;
            }
        }
    }
  • 相关阅读:
    Python与Flask
    Python与MySQL
    range,map,sum
    Java:初始化类、变量、程序块加载解析
    HTML_记录2
    HTML_记录1
    查看当前连接的实例名
    expdp impdp
    行列转换
    oracle创建定时任务
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11340489.html
Copyright © 2011-2022 走看看