165. Compare Version Numbers
题目描述:
比较版本号,前导零可以忽略,从左到右,v1大就返回1,v2大就返回2,否则返回0。
Example 1:
Input: version1 = "1.01", version2 = "1.001"
Output: 0
Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1".
Example 2:
Input: version1 = "1.0", version2 = "1.0.0"
Output: 0
Explanation: version1 does not specify revision 2, which means it is treated as "0".
Example 3:
Input: version1 = "0.1", version2 = "1.1"
Output: -1
Explanation: version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2.
思路代码:
1、和链表求和类似,不够长就补一个0(默认值)直到比出结果、或遍历完较长的那个串。
不用 split()
的话,双指针分别比较也行。
class Solution {
public int compareVersion(String v1, String v2) {
String[] ss1 = v1.split("\\."); // regex should be "\\."
String[] ss2 = v2.split("\\.");
int n1 = ss1.length, n2 = ss2.length, i = 0;
while (i < n1 || i < n2) {
int num1 = i >= n1 ? 0 : parse(ss1[i]);
int num2 = i >= n2 ? 0 : parse(ss2[i]);
if (num1 < num2) return -1;
if (num1 > num2) return 1;
++i;
}
return 0;
}
int parse(String s) {
return Integer.valueOf(s);
}
}
Runtime: 1 ms, faster than 90.83% of Java online submissions for Compare Version Numbers.
Memory Usage: 42.3 MB, less than 11.72% of Java online submissions for Compare Version Numbers.
p.s. 一个小细节
2、 题解区大佬的解法,用上了Integer
的n1.compareTo(n2)
public int compareVersion(String version1, String version2) {
String[] levels1 = version1.split("\\.");
String[] levels2 = version2.split("\\.");
int length = Math.max(levels1.length, levels2.length);
for (int i=0; i<length; i++) {
Integer v1 = i < levels1.length ? Integer.parseInt(levels1[i]) : 0;
Integer v2 = i < levels2.length ? Integer.parseInt(levels2[i]) : 0;
int compare = v1.compareTo(v2);
if (compare != 0) {
return compare;
}
}
return 0;
}
// https://leetcode.com/problems/compare-version-numbers/discuss/50774/Accepted-small-Java-solution.