ID | Title | Difficulty | |
---|---|---|---|
Loading... |
186. Reverse Words in a String II
Medium
LeetCode
Two Pointers, String
Problem
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?
Code
class Solution {
public void reverseWords(char[] str) {
if(str == null || str.length <= 1) return;
reverse(str, 0, str.length - 1);
int index = 0;
int start = 0;
// 注意处理最后一个
while(index <= str.length){
if(index == str.length || str[index] == ' '){
reverse(str, start, index - 1);
start = index + 1;
}
index++;
}
}
private void reverse(char[] str, int start, int end){
while(start < end){
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
}
按 <- 键看上一题!
185. Department Top Three Salaries
按 -> 键看下一题!
187. Repeated DNA Sequences