思路
字符串根据"."得到每段的数字,依次进行比较即可。
follow up:
考虑尽可能多的corner case,判断输入的version是否合法。
复杂度
时间复杂度O(n), 空间复杂度O(1)
代码
class Solution {
public int compareVersion(String version1, String version2) {
// Compare each character in 2 strings.// The larger string wins// Longer string wins: one of the 2 strings hits the end, and they are the same so far. int index1 = 0, index2 = 0;while(index1 < version1.length() || index2 < version2.length()) {
int v1 = 0, v2 = 0;while(index1 < version1.length() && version1.charAt(index1) != '.') {
v1 *= 10;v1 += version1.charAt(index1) - '0';index1++;}while(index2 < version2.length() && version2.charAt(index2) != '.') {
v2 *= 10;v2 += version2.charAt(index2) - '0';index2++;}if(v1 < v2) return -1;if(v1 > v2) return 1;// or infinite loop occursindex1++;index2++;}return 0;}
}