Today, the first question in leetcode is a simple string reverse output problem. The following is my code:
public String reverseWords(String s) { if(s == null) return new String(""); StringBuffer fir = new StringBuffer(s); if(fir.length() == 0) return new String(""); while(fir.length() != 0 && fir.charAt(0) == ‘ ‘){ fir = fir.deleteCharAt(0); } if(fir.length() == 0) return new String(""); StringBuffer res = new StringBuffer(); String son[] = fir.toString().split(" "); for(int i = son.length - 1; i > 0; i--){ //if(son[i].length() == 0) continue; son[i] = son[i].trim(); res.append(son[i] + " "); } res.append(son[0].trim()); return res.toString(); }
When I use split ("") to cut a string, if consecutive spaces exist, the substring that contains only one space should be cut out, however, the comments in the Code successfully process the substrings that only contain spaces so that they do not appear in the returned results.
That is to say, if the comment row keeps the comment, call: S. reversewords ("this is a blog"), the output will be: "Blog A is this". Note that there are two spaces in the middle of each word, however, if you cancel the comment statement, the result is: "Blog A is this". Here, each word is separated by only one space.
This situation is a bit confusing. I wonder if I can give some insights, so I am afraid that I will forget it. I will put the problem here first...