首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

LeetCode Compare Version Numbers:版本號字符串比較

     編輯:關於C++

LeetCode Compare Version Numbers 詳解

題目:給定兩個版本號字符串 version1, version2(如 "1.0.1"、"1"),按 . 分割為修訂號,從左到右逐段比較整數值。缺失段視為 0。返回 1/0/-1 表示大/等/小。

核心邏輯:分割 → 整數化 → 對齊比較

  1. 用 . 分割字符串為片段陣列。
  2. 將每段轉為整數(自動去除前導零)。
  3. 雙指針遍歷兩陣列,較短者補 0。
  4. 首個不等段決定結果;全等則返回 0。

參考代碼 (C++ / Python / Java)

// 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;
    }
}

關鍵測試用例

version1version2結果說明
1.0.1111.0.1 > 1.0.0
1.01.0.00尾部 0 忽略
0.11.1-1首段決定
1.011.0010前導零無影響
1.01.0.0.00多段 0 等價

常見錯誤

  • ❌ 直接字符串比較:"1.10" < "1.2"(字典序錯誤)。
  • ❌ 忽略尾部 0:1.0 != 1。
  • ❌ 整數溢出:修訂號可能超過 32 位(題目未限制),用 long/BigInteger 或逐位字符串比較(去前導零後比長度再比字典序)。

複雜度分析

指標複雜度說明
時間O(L)L 為字符串總長度
空間O(L)分割後的陣列

總結

Compare Version Numbers 是字符串處理基礎題。核心在於按分隔符分割、整數化比較、缺位補零。注意大數處理(可用逐位比較避免溢出)與尾部零語義。此邏輯直接適用於軟體版本管理、依賴解析、API 版本協商等實際場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved