zoukankan      html  css  js  c++  java
  • [LC] 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.

    class Solution {
        public String reverseWords(String s) {
            if (s == null || s.length() == 0) {
                return s;
            }
            int slow = -1;
            char[] charArr = s.toCharArray();
            for (int i = 0; i < charArr.length; i++) {
                if (charArr[i] != ' ' && (i == 0 ||charArr[i - 1] == ' ')) {
                    slow = i;
                }
                if (charArr[i] != ' ' && (i == charArr.length - 1 || charArr[i + 1] == ' ')) {
                    reverse(slow, i, charArr);
                }
            }
            return new String(charArr);
        }
        
        private void reverse(int start, int end, char[] charArr) {
            while (start <= end) {
                char tmp = charArr[start];
                charArr[start] = charArr[end];
                charArr[end] = tmp;
                start += 1;
                end -= 1;
            }
        }
    }
  • 相关阅读:
    CentOS随笔
    CentOS随笔
    CentOS随笔
    CentOS随笔
    产品从生到死的N宗罪
    即将结束的2015。
    Mvvm
    android 热补丁修复框架
    反编译APK
    关于短视频
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12132263.html
Copyright © 2011-2022 走看看