跳转至

165.比较版本号 (Medium)*

题目描述*

思路 & 代码*

注意到示例里有一个是 1.0 == 1.0.0,所以不能直接比较字符串。用字符串流处理,需要注意条件不能写成 s1 >> num1 || s2 >> num2,会短路。

class Solution {
public:
    int compareVersion(string version1, string version2) {
        char c;
        istringstream s1(version1);
        istringstream s2(version2);
        int num1 = 0, num2 = 0;
        while(static_cast<bool>(s1 >> num1) + static_cast<bool>(s2 >> num2)) {
            if(num1 > num2) {
                return 1;
            }else if(num1 < num2) {
                return -1;
            }else {
                num1 = num2 = 0;
                s1 >> c, s2 >> c;
            }
        }
        return 0;
    }
};
class Solution {
public:
    int compareVersion(string version1, string version2) {
        int i = 0, j = 0;
        int len1 = version1.size(), len2 = version2.size();
        while(i < len1 || j < len2) {
            int num1 = 0, num2 = 0;
            while(i < len1 && version1[i] != '.') {
                num1 = num1 * 10 + version1[i++] - '0';
            }
            while(j < len2 && version2[j] != '.') {
                num2 = num2 * 10 + version2[j++] - '0';
            }
            if(num1 > num2) {
                return 1;
            }else if(num1 < num2) {
                return -1;
            }
            i++, j++;
        }
        return 0;
    }
};

最后更新: July 23, 2022