同 5407,比較兩個版本號字符串。
避免 split 產生數組開銷,直接在字符串上雙指針解析數字段。
public class Solution {
public int compareVersion(String v1, String v2) {
int i = 0, j = 0;
while (i < v1.length() || j < v2.length()) {
int x1 = 0, x2 = 0;
while (i < v1.length() && v1.charAt(i) != '.') x1 = x1 * 10 + (v1.charAt(i++) - '0');
while (j < v2.length() && v2.charAt(j) != '.') x2 = x2 * 10 + (v2.charAt(j++) - '0');
if (x1 > x2) return 1;
if (x1 < x2) return -1;
i++; j++; // 跳過 '.'
}
return 0;
}
}