題目:給定兩個版本號字符串 version1, version2(如 "1.0.1"、"1"),按 . 分割為修訂號,從左到右逐段比較整數值。缺失段視為 0。返回 1/0/-1 表示大/等/小。
. 分割字符串為片段陣列。// C++
class Solution {
public:
int compareVersion(string v1, string v2) {
auto split = [](const string& s) {
vector parts;
string cur;
for (char c : s) {
if (c == '.') { parts.push_back(stoi(cur)); cur.clear(); }
else cur.push_back(c);
}
if (!cur.empty()) parts.push_back(stoi(cur));
return parts;
};
vector a = split(v1), b = split(v2);
int n = max(a.size(), b.size());
for (int i = 0; i < n; ++i) {
int x = (i < a.size()) ? a[i] : 0;
int y = (i < b.size()) ? b[i] : 0;
if (x > y) return 1;
if (x < y) return -1;
}
return 0;
}
};
# Python
class Solution:
def compareVersion(self, v1: str, v2: str) -> int:
a = list(map(int, v1.split('.')))
b = list(map(int, v2.split('.')))
n = max(len(a), len(b))
for i in range(n):
x = a[i] if i < len(a) else 0
y = b[i] if i < len(b) else 0
if x > y: return 1
if x < y: return -1
return 0
// Java
class Solution {
public int compareVersion(String v1, String v2) {
String[] a = v1.split("\\.");
String[] b = v2.split("\\.");
int n = Math.max(a.length, b.length);
for (int i = 0; i < n; i++) {
int x = i < a.length ? Integer.parseInt(a[i]) : 0;
int y = i < b.length ? Integer.parseInt(b[i]) : 0;
if (x > y) return 1;
if (x < y) return -1;
}
return 0;
}
}
| version1 | version2 | 結果 | 說明 |
|---|---|---|---|
| 1.0.1 | 1 | 1 | 1.0.1 > 1.0.0 |
| 1.0 | 1.0.0 | 0 | 尾部 0 忽略 |
| 0.1 | 1.1 | -1 | 首段決定 |
| 1.01 | 1.001 | 0 | 前導零無影響 |
| 1.0 | 1.0.0.0 | 0 | 多段 0 等價 |
"1.10" < "1.2"(字典序錯誤)。1.0 != 1。long/BigInteger 或逐位字符串比較(去前導零後比長度再比字典序)。| 指標 | 複雜度 | 說明 |
|---|---|---|
| 時間 | O(L) | L 為字符串總長度 |
| 空間 | O(L) | 分割後的陣列 |
Compare Version Numbers 是字符串處理基礎題。核心在於按分隔符分割、整數化比較、缺位補零。注意大數處理(可用逐位比較避免溢出)與尾部零語義。此邏輯直接適用於軟體版本管理、依賴解析、API 版本協商等實際場景。