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--;
            }
        }
    }
  • 相关阅读:
    class-dump + DumpFrameworks.pl
    使用 U盘 重装 Mac OSX
    本地化应用程序
    UINavigationBar 总结
    Xcode 杂七杂八
    App 打包并跳过 AppStore 的发布下载
    Summary of Mac Versions
    QT5安装(null)
    如何实现LAN或WAN远程开机?
    DELL 8700重装系统
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11340489.html
Copyright © 2011-2022 走看看