• 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

  • 相关阅读:
    Show me the Template
    WPF中的Style(风格,样式)
    像苹果工具条一样平滑连续地缩放
    为窗体添加 "最大化","最小化","还原"等 事件
    [CHM]果壳中的XAML(XAML in a Nutshell)
    我的简约播放器
    很好玩的滚动效果
    项目经验分享(上)
    通过mongodb客户端samus代码研究解决问题
    记录数据库执行情况来分析数据库查询性能问题
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4491656.html
Copyright © 2020-2023  润新知