LeetCode 165 比较版本号

LeetCode 165 比较版本号

🟡 中等 https://leetcode.cn/problems/compare-version-numbers/description/

在经历一系列的尝试失败后,两个数据的长度不一是关键影响因素,因此对齐两个数据,所以短的应该补0,实际可以不用补,设置初始值为0即可。

class Solution {

public:

    int compareVersion(string version1, string version2) {

        int fast1 = 0;

        int fast2 = 0;

        int n1 = version1.size();

        int n2 = version2.size();

        while(fast1<n1||fast2<n2){

            int v1 = 0;

            if(fast1<n1){

                int slow1 =fast1;

                while(fast1<n1&&version1[fast1]!='.') fast1++;

                v1 = stoi(version1.substr(slow1,fast1-1-slow1+1));

            }

            int v2 = 0;

            if(fast2<n2){

                int slow2 = fast2;

                while(fast2<n2&&version2[fast2]!='.') fast2++;

                v2 = stoi(version2.substr(slow2,fast2-1-slow2+1));

            }

            if(v1<v2) return -1;

            if(v1>v2) return 1;

            fast1++;

            fast2++;

        }

        return 0;

    }

};