[英]Checking if an array of string is sorted lexicographically case insensitive
我正在寫一個方法,該方法將輸入字符串數組和整數n
作為輸入。 該方法將檢查直到長度n
之前的字符串是否按字典順序排列。 我的代碼為每個輸入都返回false,我不知道為什么!
public static boolean isStringArraySorted(String[] strs, int n) {
boolean answer=true;
for (String word : strs) {
for(int i=1; i<strs.length; i++) {
String check1 =word.substring(0,n);
String check2= strs[i].substring(0,n);
if ( check1.compareToIgnoreCase(check2) > 0 )
return false;
}
}
return answer;
}
將您的循環更改為此:
for (int j=0; j<strs.length; j++){
for(int i=j+1; i<strs.length; i++){
String word = strs[j];
String check1 =word.substring(0,n);
String check2= strs[i].substring(0,n);
if (check1.compareToIgnoreCase(check2)>0)
return false;
}
}
由於您做錯的關鍵是您的第二個循環從錯誤的位置開始。
因為您在整個數組的內部for循環中進行迭代,而您僅應從單詞開始進行迭代。
for (int j=1; j<strs.length; j++){
for(int i=j+1; i<strs.length; i++){
String word = strs[j];
String check1 =word.substring(0,n);
String check2= strs[i].substring(0,n);
if (check1.compareToIgnoreCase(check2)>0)
return false;
}
}
正如我在評論中提到的,您只需要一個循環即可解決此問題:
public static boolean isStringArraySorted(String[] strs, int n) {
for (int i = 0; i < strs.length - 1; i++) {
String first = substring(strs[i], n);
String second = substring(strs[i + 1], n);
if (first.compareToIgnoreCase(second) > 0) {
return false;
}
}
return true;
}
private static String substring(String s, int n) {
return s.substring(0, n > s.length() ? s.length() - 1 : n);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.