Friday, November 27, 2015

[leetcode]Reverse Words in a String II

这里的妙处是把每个单词都先翻转 然后整个翻转
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
    public void reverseWords(char[] s) {
        int current = 0;
        for (int i = 0; i < s.length; i++){
            if (i == s.length-1||s[i+1] == ' '){
                reverse(s, current, i);
                current = i+2;
            }
        }
        reverse(s, 0, s.length-1);
    }
    
    private void reverse(char[]s, int start, int end){
        while (start < end){
            char temp = s[start];
            s[start] = s[end];
            s[end] = temp;
            end--;
            start++;
        }
    }
}

No comments:

Post a Comment