我得到了数字作为单词:
{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
数字最多只有 10 个。我的任务是将给定的两个输入字符串相互比较。当您比较两个数字时,它基本上应该起作用:
compare(1, 1) -> 0;
compare(1, 3) -> 1 < 3 as -1;
compare(5, 2) -> 5 > 2 as 1;
像这样比较两个字符串的最佳方法是什么?结果看起来像这样:
compare("one", "one") -> 0;
compare("one", "three") -> -1;
compare("five", "two") -> 1;
public int compare(String a, String b) {
return 0;
}
最佳答案
您可以使用映射对字符串及其值进行编码。这种方法的好处是它有 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));
}
完整示例: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"));
}
}
输出:0
-1
1
另一种解决方案是使用 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"));
}
}
输出:0
-1
1
关于java - 用数字作为单词比较两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66857504/