lintcode53 Reverse Words in a String -easy
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
- 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
1. 暴力的stack法。
import java.util.Stack; public class Solution { /* * @param s: A string * @return: A string */ public String reverseWords(String s) { // write your code here if(s == null){ return null; } if(s.length() == 0){ return new String(); } Stack<String> stack = new Stack<String>(); int head = 0; int tail = 0; while(head < s.length()){ while(head < s.length() && s.charAt(head) == ' '){ head++; } tail = head; while(tail < s.length() && s.charAt(tail) != ' '){ tail ++; } if(head >= s.length() || tail > s.length()){ break; } stack.push(s.substring(head, tail)); head = tail; } String reversed = new String(); while (!stack.isEmpty()){ reversed += stack.pop(); reversed += " "; } if(reversed.length() > 0){ reversed = reversed.substring(0, reversed.length() -1); } return reversed; } }
1. str.substring(int, int); 而不是str.subString(int, int);
2. substring(int beginIndex,int endIndex)从指定的 beginIndex 处开始,直到索引 endIndex - 1 处的字符。因此,该子字符串的长度为 endIndex-beginIndex。 "smiles".substring(1, 5) returns "mile"
3. 在塞完所有单词到stack里后,最后一个个拿出来打印的时候,切记切记循环体for()里面不可以是int i = 0; i < stack.size(); i++!,因为你for{}里面的操作有在pop,那你等于size这个值就一直在变!可以
int wordCount = stack.size(); if(!stack.isEmpty()){ for(int i = 0; i < wordCount - 1; i++){ reversed+= stack.pop(); reversed+= " "; } reversed += stack.pop(); }
或者
while (!stack.isEmpty()){ reversed += stack.pop(); reversed += " "; } if(reversed.length() > 0){ reversed = reversed.substring(0, reversed.length() -1); }
}
4.注意关注输入处理,null, "", " "。在心里跑一下他们
2. 巧妙的利用String里面的split方法:
import java.util.Stack; public class Solution { /* * @param s: A string * @return: A string */ public String reverseWords(String s) { // write your code here if (s == null || s.length() == 0){ return ""; } String res = ""; String[] split = s.split(" "); for (int i = split.length - 1; i >= 0; i--){ if (!split[i].equals("") && !split[i].equals(" ")){ res += split[i]; res += " "; } } if (res.length() > 0){ res = res.substring(0, res.length() - 1); } return res; } }
- String.split()方法如果用“.”作为分隔的话,必须是如下写法,String.split("\\."),这样才能正确的分隔开,不能用String.split(".”); 类似的还有| *。另外如果在一个字符串中有多个分隔符,可以用“|”作为连字符,比如,“acount=? and uu =? or n=?”,把三个都分隔出来,可以用String.split("and|or");
- 切记String的对比不要用 ==, != 。而是需要用string.equals(“xxx”);