# 返回字典序中首先出现的字符串的长度

go评论56阅读模式

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 &lt; s.length() &amp;&amp;
i &lt; t.length(); i++) {
if ((int) s.charAt(i) ==
(int) t.charAt(i)) {
continue;
} else {
return (int) s.length() -
(int) t.length();
}
}

if (s.length() &lt; t.length()) {
return (s.length() - t.length());
} else if (s.length() &gt; 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

``````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();
}
``````

``````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) &gt; 0 ? t.length() : s.length();
}
``````

# 答案2

``````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();
}
``````

Something to this effect should work I think.

``````public static int problem4(String s, String t){
if (s.compareTo(t)&gt;0)
System.out.println(t.length());
return t.length();
else
System.out.println(s.length());
return s.length();
}

problem(&quot;a&quot;, &quot;b&quot;);
``````

• 本文由 发表于 2020年10月6日 20:38:44
• 转载请务必保留本文链接：https://go.coder-hub.com/64225973.html
• java
• lexicographic

go 70

go 79

go 65

go 51