• 186. Reverse Words in a String II


    题目:

    Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.

    The input string does not contain leading or trailing spaces and the words are always separated by a single space.

    For example,
    Given s = "the sky is blue",
    return "blue is sky the".

    Could you do it in-place without allocating extra space?

    链接:  http://leetcode.com/problems/reverse-words-in-a-string-ii/

    题解:

    翻转单词II。这次给定了char array,我们就可以使用三步翻转法了。因为题目的条件很优惠,前后没有空格,单词间又只有一个空格,那我们可以省略很多边界条件的判定,先翻转整个数组,然后碰到单词就正序回来。

    Time Complexity - O(n), Space Complexity - O(1)。

    public class Solution {
        public void reverseWords(char[] s) {
            if(s == null || s.length == 0)
                return;
            reverse(s, 0, s.length - 1);
            int lo = 0;
            
            for(int i = 0; i <= s.length; i++) {
                if(i == s.length || s[i] == ' ') {
                    reverse(s, lo, i - 1);
                    lo = i + 1;
                }
            }
        }
        
        private void reverse(char[] s, int i, int j) {
            while(i < j)
                swap(s, i++, j--);
        }
        
        private void swap(char[] s, int i, int j) {
            char tmp = s[i];
            s[i] = s[j];
            s[j] = tmp;
        }
    }

    题外话:

    同事要去南极玩,先飞到阿根廷,再到乌斯怀亚,然后坐科考船过去。科考船一套大概10500刀,机票另算,好爽啊。以后我也要好好去旅游。

    二刷:

    跟一刷基本一样

    Java:

    public class Solution {
        public void reverseWords(char[] s) {
            if (s == null || s.length < 2) return;
            int len = s.length;
            reverse(s, 0, len - 1);
            int lo = 0;
            for (int i = 0; i < len; i++) {
                if (s[i] == ' ') {
                    reverse(s, lo, i - 1);
                    lo = i + 1;
                }
            }
            reverse(s, lo, len - 1);
        }
        
        private void reverse(char[] s, int lo, int hi) {
            while (lo < hi) {
                char tmp = s[lo];
                s[lo] = s[hi];
                s[hi] = tmp;
                lo++;
                hi--;
            }
        }
    }

    Reference:

    http://www.zhihu.com/question/19857821

  • 相关阅读:
    canvas 学习
    configure/autoconf/automake文件相关
    git add A 和 git add . 的区别详解
    Vim格Vim格式化代码功能——gg=G式化代码功能——gg=G
    详解git commit amend 用法
    git reset HEAD 与 git reset hard HEAD的区别 天地逍遥
    git的撤销操作:reset、checkout和revert
    参与linux社区
    git制作补丁
    git diff、git diff head、git diff cached三者详细区分
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4491656.html
Copyright © 2020-2023  润新知