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

  • 相关阅读:
    Redis基础学习(三)—Key操作
    Redis基础学习(二)—数据类型
    Redis基础学习(一)—Redis的安装
    Bootstrap基础学习(二)—表单
    Bootstrap基础学习(一)—表格与按钮
    List去除重复的元素
    jQuery 将表单序列化为Json对象
    SpringMVC基础学习(三)—参数绑定
    CentOS 7.1安装Elasticsearch和Storm
    Python多线程中join函数与setDaemon函数使用说明
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4491656.html
Copyright © 2011-2022 走看看