我撰寫了如下代碼,但它沒有正確回傳第一個重復出現的字母。
例子:
在單詞"statistics"中重復出現的字母是s,t和i。但是該字母t比字母sand更快地出現i,但我的程式回傳s而不是t。
根據手頭的任務,我需要做什么才能回傳t,使用兩個 for 回圈?
public class Main {
public static char FRL(String word){
for(int i = 0; i<word.length(); i ){
for(int j = i 1; j<word.length(); j ){
if(word.charAt(i) == word.charAt(j)){
return word.charAt(i);
}
}
}
return '0';
}
public static void main(String[] args) {
String word = "statistics";
if (FRL(word) != '0'){
System.out.println(FRL(word));
}else{
System.out.println("No reccurring letter!");
}
}
}
uj5u.com熱心網友回復:
您可以通過將每個遇到的字符存盤在 a 中來減少嵌套回圈并提高性能HashSet:
public static char FRL(String word){
Set<Character> seen = new HashSet<>();
for(int i = 0; i < word.length(); i ) {
char next = word.charAt(i);
if (!seen.add(next)) {
return next;
}
}
return '0';
}
但是如果你需要使用嵌套回圈,那么你應該修復內部回圈的初始化運算式和條件for,即我們應該檢查從0包含索引到i不包含索引的字符:
public static char FRL(String word) {
for(int i = 0; i < word.length(); i ) {
char next = word.charAt(i);
for(int j = 0; j < i; j ){
if(next == word.charAt(j)) {
return next;
}
}
}
return '0';
}
順便說一句,getFirstRecuringLetter()這將是一個比FRL.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/479424.html
