The*_*irl 4 java string numbers string-comparison
我得到了数字作为单词:
{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
Run Code Online (Sandbox Code Playgroud)
数字最多只有 10 个。我的任务是将给定的两个输入字符串相互比较。
当您比较两个数字时,它基本上应该起作用:
compare(1, 1) -> 0;
compare(1, 3) -> 1 < 3 as -1;
compare(5, 2) -> 5 > 2 as 1;
Run Code Online (Sandbox Code Playgroud)
像这样比较两个字符串的最佳方法是什么?
结果看起来像这样:
compare("one", "one") -> 0;
compare("one", "three") -> -1;
compare("five", "two") -> 1;
Run Code Online (Sandbox Code Playgroud)
{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
Run Code Online (Sandbox Code Playgroud)
您可以使用映射对字符串及其值进行编码。这种方法的好处是它具有O(1)与使用数组相反的复杂性。
Map<String, Integer> map = Map.of("one", 1, "two", 2, ...);
public int compare(String a, String b) {
return Integer.compare(map.get(a),map.get(b));
}
Run Code Online (Sandbox Code Playgroud)
完整示例:
public class Example {
private final static Map<String, Integer> STRING_VALUE =
Map.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5,
"six", 6, "seven", 7, "eight", 8, "nine", 9, "ten", 10);
public static int compare(String a, String b) {
return Integer.compare(STRING_VALUE.get(a),STRING_VALUE.get(b));
}
public static void main(String[] args) {
System.out.println(compare("one", "one"));
System.out.println(compare("one", "three"));
System.out.println(compare("five", "two"));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
0
-1
1
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是使用 ENUM:
完整示例:
public class Example {
enum Values {
ONE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN;
}
public static int compare(String a, String b) {
Values vA = Values.valueOf(a.toUpperCase());
Values vB = Values.valueOf(b.toUpperCase());
return Integer.compare(vA.compareTo(vB), 0);
}
public static void main(String[] args) {
System.out.println(compare("one", "one"));
System.out.println(compare("one", "three"));
System.out.println(compare("five", "two"));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
0
-1
1
Run Code Online (Sandbox Code Playgroud)
这是另一种方式。
String s = "onetwothreefourfivesixseveneightnineten";
int compare(String a, String b) {
return Integer.compare(s.indexOf(a),s.indexOf(b));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
219 次 |
| 最近记录: |