Reverse Words in a String
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
思路:确定好每一个字符串,然后加入到ArrayList中,字符串由前后空格分隔
java代码:
- public String reverseWords(String s) {
- ArrayList<String> res = new ArrayList<String>();
- int slen = s.length();
- int index = 0;
- while(true) {
- while(index<slen&&s.charAt(index)==' ') index++;
- if(index>=slen) break;
- int start = index;
- while(index<slen && s.charAt(index)!=' ') index++;
- int end = index;
- String str = s.substring(start,end);
- res.add(str);
- }
- StringBuffer strBuffer = new StringBuffer();
- if(res.size()==0) return "";
- strBuffer.append(res.get(res.size()-1));
- for(int i=res.size()-2;i>=0;i--) {
- strBuffer.append(" ");
- strBuffer.append(res.get(i));
- }
- return strBuffer.toString();
- }

浙公网安备 33010602011771号