leetcode165 - Compare Version Numbers - medium
Compare two version numbers version1 and version2.
If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.
Example 1:
Input: version1 = "0.1", version2 = "1.1"
Output: -1
Example 2:
Input: version1 = "1.0.1", version2 = "1"
Output: 1
Example 3:
Input: version1 = "7.5.2.4", version2 = "7.5.3"
Output: -1
字符串处理。
1.split(“\\.”)
2.按两者更长的数组遍历过去。如果其中一个取不到数字了,就取0作为当前的数。(即隐形把1.0.1, 1.0的比较转为1.0.1, 1.0.0的比较)。
细节:
1.split(“.”)中的.是字符串匹配的任意单个字符的那张百搭牌!如果你想要声明literally的.来分割,比如这题,就要用split(“\\.”)。
2.注意corner case: 1.0和1是相等的!所以你不能只比到两者公共长度就结束了,后面的还得看是不是都为0. 但先比公共part再看后面是否为0的写法太不优雅了(参见我的辣鸡写法)。请换个思路,对比两者中更长的长度,如果取不到则补0接着对比的写法(参见leetcode摘抄写法)。
我的实现:
class Solution { public int compareVersion(String version1, String version2) { // P1: 注意.的分隔符 String[] nums1 = version1.split("\\."); String[] nums2 = version2.split("\\."); int i = 0; while (i < nums1.length && i < nums2.length) { int n1 = Integer.parseInt(nums1[i]); int n2 = Integer.parseInt(nums2[i]); if (n1 < n2) { return -1; } else if (n1 > n2) { return 1; } else { i++; } } if (nums1.length == nums2.length) { return 0; } // P2: case 1.0和1是相等的! while (i < nums2.length) { if (Integer.parseInt(nums2[i++]) != 0) { return -1; } } while (i < nums1.length) { if (Integer.parseInt(nums1[i++]) != 0) { return 1; } } return 0; } }
leetcode陈独秀网友实现:
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; }