首页 > 其他 > 详细

186. Reverse Words in a String II - Medium

时间:2019-08-12 16:19:11      阅读:89      评论:0      收藏:0      [点我收藏+]

Given an input string , reverse the string word by word. 

Example:

Input:  ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]

Note: 

  • A word is defined as a sequence of non-space characters.
  • The input string does not contain leading or trailing spaces.
  • The words are always separated by a single space.

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

 

two pointers

time: O(n), space: O(1)

class Solution {
    public void reverseWords(char[] s) {
        reverse(s, 0, s.length - 1);
        int i = 0, j = 0;
        while(j < s.length) {
            if(s[j] == ‘ ‘) {
                reverse(s, i, j - 1);
                j++;
                i = j;
            } else {
                j++;
            }
        }
        reverse(s, i, j - 1);
    }
    
    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--;
        }
    }
}

 

186. Reverse Words in a String II - Medium

原文:https://www.cnblogs.com/fatttcat/p/11340353.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!