試圖為學校解決這個問題
“給定一個字串 s 和一個字符 c,回傳一個與 s 長度相同的整數的新串列,其中對于每個索引 i,它的值設定為 s[i] 到 c 的最近距離。您可以假設 c 存在于 s 中。 "
例如
輸入 s = "aabaab" c = "b"
輸出 [2, 1, 0, 1, 1, 0]
我的輸出 [63,63,64,63,63]
我無法弄清楚我做錯了什么,我該怎么辦?
public static void main(String []Args) {
String s = "aabaab";
String c = "b";
List<Integer> list = new ArrayList<Integer>();
char[] ch = s.toCharArray();
int indexofc = new String(ch).indexOf(c);
for(int i=0;i<ch.length;i ) {
int indexofothers = ch[i];
int result = indexofothers - indexofc;
if (result<=0) {
result = result*(-1);
}
list.add(result);
}
System.out.println(list);
}
}
uj5u.com熱心網友回復:
您的代碼有兩個主要問題:首先,這一行沒有意義
int indexofothers = ch[i];
您正在嘗試獲取索引,但取而代之的是在該位置獲取字符,i然后將其轉換為可能導致類似于 63 的整數。所以使用i而不是ch[i].
其次,如果您像這樣使用它,indexOf 方法只會回傳第一個索引。添加當前索引(并將其移動到回圈中),否則您將始終獲得到第一個 b 的距離。因此,您的代碼可能如下所示:
public static void main(String []Args) {
String s = "aabaab";
String c = "b";
List<Integer> list = new ArrayList<>();
char[] ch = s.toCharArray();
for(int i=0;i<ch.length;i ) {
int indexofc = s.indexOf(c, i);
int result = i - indexofc;
if (result<=0) {
result = result*(-1);
}
list.add(result);
}
System.out.println(list);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/437297.html
下一篇:在SQL中按日期計算累積百分比
