我需要在 Java 中創建一個程式來查找所有出現的 4 字母字串,在這種情況下"lane",在給定的字串中。
比較應該不區分大小寫,并且在評估子字串是否匹配時,不應考慮匹配子字串的第二個字母。
我當前的代碼可以處理某些情況,但在其他情況下,它會回傳錯誤的出現次數或生成IndexOutOfBoundsException.
我嘗試了以下情況:
"Lanee"-1按預期回傳("Lane"匹配"lane")。"LineLone"-2按預期回傳("Line"和“Lone”match“lane”`)。"LLoenLL"- 產生一個IndexOutOfBoundsException."enaLLLmnee"- 回傳0,但應該是1"LLONElllneL"- 產生一個IndexOutOfBoundsException.
我的代碼:
public class Stringer {
public Stringer() {}
public int getOccurrences(String s) {
String lower = s.toLowerCase();
int occurrences = 0;
int x = 0;
while (x < lower.length()) {
int traverser = lower.indexOf("l", x);
if (traverser != -1 && lower.length() > 3) {
String sub = lower.substring(x = 2, x = 2);
if (sub.equals("ne")) {
occurrences ;
}
} else {
break;
}
}
return occurrences;
}
}
我該如何解決這個問題?
uj5u.com熱心網友回復:
基本上,您需要遍歷給定的字串,檢查當前字符是否等于'l'(的第一個字符 "lane")。
如果是這種情況,您需要檢查當前索引處的 if 字符 2并分別 3匹配'n'和'e'。如果所有這些字符都匹配,則應增加出現次數并將索引推進,3以避免重復檢查相同的位置。
請注意,回圈中的終止條件是 i < lower.length() - 3 因為目標字串的長度 "lane"是4 ,并且在檢查 index 處子字串的第一個字符時, i 我們需要能夠檢查 index 處的最后一個子字串字符 i 3。
public static int getOccurrences(String s) {
String lower = s.toLowerCase();
int occurrences = 0;
for (int i = 0; i < lower.length() - 3; i ) {
if (lower.charAt(i) == 'l' &&
lower.charAt(i 2) == 'n' &&
lower.charAt(i 3) == 'e') {
occurrences ; // incrementing the number of occurrences
i = 3; // advancing the index
}
}
return occurrences;
}
main()
public static void main(String[] args) {
System.out.println(getOccurrences("Lanee"));
System.out.println(getOccurrences("LineLone"));
System.out.println(getOccurrences("LLoenLL"));
System.out.println(getOccurrences("enaLLLmnee"));
System.out.println(getOccurrences("LLONElllneL"));
}
輸出:
1
2
0
1
2
uj5u.com熱心網友回復:
您也可以使用正則運算式來解決這個問題。
public static void main(String[] args) {
System.out.println(getOccurrences("Lanee"));
System.out.println(getOccurrences("LineLone"));
System.out.println(getOccurrences("LLoenLL"));
System.out.println(getOccurrences("enaLLLmnee"));
System.out.println(getOccurrences("LLONElllneL"));
}
印刷
1
2
0
1
2
正則運算式可用于匹配字串中的模式
(?i)- 使用i匹配時忽略大小寫的標志l.ne- 是要匹配的字串。代表.任何字符- Matcher 獲取源字串并遍歷字串以查找匹配項。如果它回傳 true,則更新計數。
public static int getOccurrences(String s) {
Matcher m = Pattern.compile("(?i)l.ne").matcher(s);
int count = 0;
while (m.find()) {
count ;
}
return count;
}
您還可以使用以下方法簽名來獲取目標字串。然后您只需要使用目標構建運算式。
public static int getOccurrences(String s, String target) {
String expression = "(?i)" target.substring(0,1) "." target.substring(2);
Matcher m = Pattern.compile(expression).matcher(s);
int count = 0;
while (m.find()) {
count ;
}
return count;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/532356.html
標籤:爪哇细绳算法
