Given an input string, reverse the string word by word.正则表达式
For example, Given s = "the sky is blue", return "blue is sky the".数组
Update (2015-02-12): For C programmers: Try to solve it in-place in O(1) spaceapp
时间 O(N) 空间 O(N)ui
将单词根据空格split开来存入一个字符串数组,而后将该数组反转便可。spa
先用trim()将先后无用的空格去掉指针
用正则表达式" +"来匹配一个或多个空格code
public class Solution { public String reverseWords(String s) { String[] words = s.trim().split(" +"); int len = words.length; StringBuilder result = new StringBuilder(); for(int i = len -1; i>=0;i--){ result.append(words[i]); if(i!=0) result.append(" "); } return result.toString(); } }
时间 O(N) 空间 O(N) 若是输入时char数组则是O(1)字符串
先将字符串转换成char的数组,而后将整个数组反转。而后咱们再对每个单词单独的反转一次,方法是用两个指针记录当前单词的起始位置和终止位置,遇到空格就进入下一个单词。input
public class Solution { public String reverseWords(String s) { s = s.trim(); char[] str = s.toCharArray(); // 先反转整个数组 reverse(str, 0, str.length - 1); int start = 0, end = 0; for(int i = 0; i < s.length(); i++){ if(str[i]!=' '){ end++; } else { // 反转每一个单词 reverse(str, start, end - 1); end++; start = end; } } return String.valueOf(str); } public void reverse(char[] str, int start, int end){ while(start < end){ char tmp = str[start]; str[start] = str[end]; str[end] = tmp; start++; end--; } } }
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.string
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?
时间 O(N) 空间 O(1)
这题就是Java版的Inplace作法了,先反转整个数组,再对每一个词反转。
public class Solution { public void reverseWords(char[] s) { reverse(s, 0, s.length - 1); int start = 0; for(int i = 0; i < s.length; i++){ if(s[i] == ' '){ reverse(s, start, i - 1); start = i + 1; } } reverse(s, start, s.length - 1); } public void reverse(char[] s, int start, int end){ while(start < end){ char tmp = s[start]; s[start] = s[end]; s[end] = tmp; start++; end--; } } }