Leetcode 151. Reverse Words in a String

public class Solution {
   public String reverseWords(String s)
	 {
		 String []v=s.split(" ");
		 /*
		 for(String x:v)
		 {
			 System.out.println(x);
		 }*/
		 String ans="";
		 for(int i=v.length-1;i>=0;i--)
		 {
			 ans+=v[i];
			 //ans+=(i==0)?"":" ";
             if(i>0)
             {
                 if(v[i-1].length()!=0)ans+=" ";//注意 字符串分割时 如果是“ 1” 结果分割成 “”(?) “1”
                 //if(v[i-1]!="")ans+=" ";//注意 Java字符串不能== https://www.cnblogs.com/Dreamice/p/7809605.html
             }
		 }
		 //System.out.println(ans);
	     return ans; 
	 }
}
注意两点 1,java字符串不能==,所有东西都是对象,完全一样,包括地址才可以 2,字符串分割如果第一个字符就是分割号,第一个被分割的是“”

Given an input string, reverse the string word by word.

Example:  

Input: "the sky is blue",
Output: "blue is sky the".

Note:

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Follow up: For C programmers, try to solve it in-place in O(1) space.

猜你喜欢

转载自blog.csdn.net/BJUT_bluecat/article/details/80933082