【发布时间】:2015-01-23 08:11:18
【问题描述】:
这是一个来自 http://www.glassdoor.com/Interview/Indeed-Software-Engineer-Interview-Questions-EI_IE100561.0,6_KO7,24.htm,具体问题
“问我一个方法,它接受一个字符串并返回最大长度的单词。可能有任意数量的空格,这让它有点棘手”
这是我的解决方案(带有测试用例)
public class MaxLength {
public static void main(String[] args) {
List<String> allWords = maxWords("Jasmine has no love for chris", 2);
for(String word: allWords){
System.out.println(word);
}
}
public static List<String> maxWords(String sentence, int length) {
String[] words = sentence.trim().split("\\s+");
List<String> list = new ArrayList<String>();
for(String word: words) {
if(word.length() <= length) {
list.add(word);
}
}
return list;
}
测试运行良好,我得到了预期的输出 - 不。然而在实际面试中,我认为面试官并不希望你从头顶知道这个正则表达式(我不必从How do I split a string with any whitespace chars as delimiters?找到它) 有没有不使用正则表达式的另一种方法来解决这个问题?
【问题讨论】:
-
this site?的问题
-
好电话,我也把它贴在他们身上
-
另外,您的方法效率低下。您可以在一次迭代中完成此操作而无需拆分。
-
我投票决定将此问题作为题外话结束,因为最好在http://codereview.stackexchange.com/提问
-
如果面试官不知道他/她的头顶
\\s+,我建议你跑,不要回头。 ;)
标签: java regex algorithm data-structures arraylist