[英]Return the length of the String that comes first lexicographically
我正在嘗試將兩個字符串傳遞給一個函數,我想返回按字典順序排在第一位的字符串的長度。
這是我迄今為止嘗試過的:
public static int problem4(String s, String t) {
for (int i = 0; i < s.length() &&
i < t.length(); i++) {
if ((int) s.charAt(i) ==
(int) t.charAt(i)) {
continue;
} else {
return (int) s.length() -
(int) t.length();
}
}
if (s.length() < t.length()) {
return (s.length() - t.length());
} else if (s.length() > t.length()) {
return (s.length() - t.length());
}
// If none of the above conditions is true,
// it implies both the strings are equal
else {
return 0;
}
}
您可以將它們設置為一個數組,並使用 Arrays.sort()。 然后像這樣檢索第一項:
public static int problem4(String s, String t) {
String[] items = new String[2];
items[0]=s;
items[1]=t;
items.sort();
return items[0].length();
}
或者你可以像這樣使用.compareTo
方法:
public static int problem4(String s, String t) {
return s.compareTo(t) > 0 ? t.length() : s.length();
}
我認為這種效果應該有效。
public static int problem4(String s, String t){
if (s.compareTo(t)>0)
System.out.println(t.length());
return t.length();
else
System.out.println(s.length());
return s.length();
}
problem("a", "b");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.