165. Compare Version Numbers

问题描述:

Compare two version numbers version1 and version2.
If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0.

You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

Example 1:

Input: version1 = "0.1", version2 = "1.1"
Output: -1

Example 2:

Input: version1 = "1.0.1", version2 = "1"
Output: 1

Example 3:

Input: version1 = "7.5.2.4", version2 = "7.5.3"
Output: -1

 

解题思路:

以 '.'为分割,获取每一个数字,每获得一个数字都要比较:

  cur1 < cur2 return -1;

  cur1 > cur2 return 1;

  cur1 == cur2 继续循环

这里需要注意的是,循环条件为i1<n1 | | i2 < n2

所以我们要对cur进行分情况赋值。

同时更新起始坐标start时,注意先增后赋值

 

代码:

class Solution {
public:
    int compareVersion(string version1, string version2) {
        int n1 = version1.size();
        int n2 = version2.size();
        int i1 = 0, i2 = 0, start1 = 0, start2 = 0;
        while(i1 < n1 || i1 < n2){
            while(i1 < n1 && version1[i1] != '.') i1++;
            while(i2 < n2 && version2[i2] != '.') i2++;
            int cur1 = i1 <= n1 ? stoi(version1.substr(start1, i1 - start1)) : 0;
            int cur2 = i2 <= n2 ? stoi(version2.substr(start2, i2 - start2)) : 0;
            if(cur1 < cur2) return -1;
            else if(cur1 > cur2) return 1;
            
            
            start1 = ++i1;
            start2 = ++i2;
        }
        return 0;
    }
};

 

posted @ 2018-08-16 08:29  妖域大都督  阅读(116)  评论(0编辑  收藏  举报