算法学习笔记(LeetCode OJ)
==================================
LeetCode的一些算法题,都是自己做的,欢迎提出改进~~
LeetCode:http://oj.leetcode.com
==================================
<Reverse Words in a String>-20140328
Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". click to show clarification.
1 public class Solution { 2 public String reverseWords(String s) { 3 s = s.trim(); 4 String[] str = s.split("\s{1,}"); 5 String tmp; 6 int len = str.length; 7 int halfLen = len/2; 8 for(int i=0;i<halfLen;i++){ 9 tmp = str[i]; 10 str[i] = str[len-i-1]; 11 str[len-i-1] = tmp; 12 } 13 StringBuffer sb = new StringBuffer(); 14 String result; 15 if(len==1){ 16 result = str[0]; 17 }else{ 18 for(String string:str){ 19 sb.append(string+" "); 20 } 21 result = sb.toString().trim(); 22 } 23 return result; 24 } 25 }
C++: http://blog.****.net/feliciafay/article/details/20884583
一个空格的情况 多个空格在一起的情况 空串的情况 首尾空格的情况 一些测试数据: “ ” “a ” " a" " a " " a b " " a b " " a b" "a b "