Friday, December 25, 2015

[Leetcode] Reverse Words in a String

Problem

Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".

Analysis

  • 首先split string by space
  • 然后 append word in reverse order
  • 注意 如果当前非空,在append下一个word之前,需要append空格

Code


// 2015/12/25
// Highlight: string split
public class Solution {
public String reverseWords(String s) {
//split string
String[] words = s.split(" ");
StringBuilder sb = new StringBuilder();
//append in reverse order
for(int i=words.length-1; i>=0; i--){
if(words[i].equals("")) continue;
if(sb.length()!=0) sb.append(" ");
sb.append(words[i]);
}
return sb.toString();
}
}

Reference

No comments:

Post a Comment