[英]Would there be an approach without using a regular expression?
這是來自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;
}
測試進行得很好,我得到了預期的輸出-不。 但是在實際面試中,我認為面試官並不希望您知道這個正則表達式(您不必從我如何用任何空白字符作為分隔符的字符串拆分中找到它)。在不使用正則表達式的情況下,還有另一種方法可以解決此問題嗎?
您可以使用StringTokenizer
。
另一種可能更長的方法是遍歷字符串並使用Character類( Character.isWhiteSpace(char c)
)提供的方法並相應地中斷字符串。
嘗試:
public static List<String> maxWords(String sentence, int length) {
List<String> list = new ArrayList<String>();
String tmp = sentence;
while (tmp.indexOf(" ") != -1) {
String word = tmp.substring(0,tmp.indexOf(" "));
tmp = tmp.substring(tmp.indexOf(" ")+1);
if(word.length() <= length) {
list.add(word);
}
}
return list;
}
好吧,您可以嘗試執行以下操作:不創建許多subStrings()
而是創建“匹配”字符串的子字符串
public class Test {
public static void main(String[] args) {
String s = "Jasmine has no love for chris";
s=s.trim();
List<String> ls = getMaxLength(s, 3);
for (String str : ls) {
System.out.println(str);
}
}
static List<String> getMaxLength(String s, int length) {
List<String> ls = new ArrayList<String>();
int i = 0;
if (s.charAt(i + length) == ' ' || i + length == s.length()) { // search if first word matches your criterion.
for (i = 1; i < length; i++) { // check for whitespace between 0 and length
if (s.charAt(i) == ' ') {
i = length;
break;
}
if (i == length - 1)
ls.add(s.substring(0, length));
}
}
for (i = length; i < s.length(); i++) {// start search from second word..
if (s.charAt(i - 1) == ' ' && i + length < s.length() // if char at length is space or end of String, make sure the char before the current char is a space.
&& (s.charAt(i + length) == ' ' || i + length == s.length())) {
for (int j = i; j < i + length; j++) {
if (s.charAt(j) == ' ') {
i = i + length;
break;
}
if (j == i + length - 1) {
ls.add(s.substring(i, i + length));
}
}
}
}
return ls;
} // end of method
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.