用数字作为单词比较两个字符串 [英] Compare two strings with numbers as words
本文介绍了用数字作为单词比较两个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到了作为单词的数字:
I have been given numbers as words:
{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
数字最多只有 10 个.我的任务是将给定的两个输入字符串相互比较.
Numbers are only up-to 10. And I my task is to compare given two input strings to each other.
当您比较两个数字时,它应该基本有效:
It should basically work as you compare two numbers:
compare(1, 1) -> 0;
compare(1, 3) -> 1 < 3 as -1;
compare(5, 2) -> 5 > 2 as 1;
像这样比较两个字符串的最佳方法是什么?
What would be the best suitable way to compare two strings like this?
结果看起来像这样:
compare("one", "one") -> 0;
compare("one", "three") -> -1;
compare("five", "two") -> 1;
public int compare(String a, String b) {
return 0;
}
推荐答案
您可以使用映射对字符串及其值进行编码.这种方法的好处是它具有 O(1)
复杂性,而不是使用数组.
You can use a map to code the Strings and their values. The benefit of this approach is that it has O(1)
complexity as oppose to use of an array for instance.
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:
Another solution is to use an 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
这篇关于用数字作为单词比较两个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文