英文:
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());
} else {
return 0;
}
}
英文:
I am trying pass two strings to a function and I want to return the length of the string that comes first lexicographically.
This is what I have tried so far:
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;
}
}
答案1
得分: 2
你可以将它们放入一个数组中,然后使用 Arrays.sort()。然后像这样检索第一个项目:
public static int problem4(String s, String t) {
String[] items = new String[2];
items[0] = s;
items[1] = t;
Arrays.sort(items);
return items[0].length();
}
或者你可以使用 .compareTo
方法,像这样:
public static int problem4(String s, String t) {
return s.compareTo(t) > 0 ? t.length() : s.length();
}
英文:
You can set them into an array, and use Arrays.sort(). Then retrieve the first item like so:
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();
}
Or you can use the .compareTo
method like so:
public static int problem4(String s, String t) {
return s.compareTo(t) > 0 ? t.length() : s.length();
}
答案2
得分: 0
以下是翻译好的代码部分:
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");
似乎有一个小错误,应该是 problem4("a", "b");
才正确。
英文:
Something to this effect should work I think.
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");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论