LeetCode-165 Compare Version Numbers

题目描述

Compare two version numbers version1and 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.

You may assume the default revision number for each level of a version number to be 0. For example, version number 3.4has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0.

 

题目大意

给两个字符串,字符串中只包含数字和‘.’,其中,‘.’将不同数字分开,分开的数字代表不同的级别,从字符串的左到右级别依次降低,即由‘.’分开的第一个子数字串为最高级别。

需要对这两个带级别的数字字符串进行大小比较,其中高级别的子串不论数值多少均大于低级别的子串代表的数值大小。若第一个字符串大于第二个字符串返回1,等于返回0,小于返回-1.

 

示例

E1

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

E2

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

E3

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

E4

Input: version1 = "1.01", version2 = "1.001"
Output: 0

E5

Input: version1 = "1.0", version2 = "1.0.0"
Output: 0

 

解题思路

遍历一遍即可,同级别进行比较,分别读取由'.'分开的子字符串并进行比较。

 

复杂度分析

时间复杂度:O(n)

空间复杂度:O(1)

 

代码

class Solution {
public:
    int compareVersion(string version1, string version2) {
        int ans = 0, len1 = version1.length(), len2 = version2.length(), i = 0, j = 0;
        while(i < len1 || j < len2) {
            int sv1 = 0;
            int sv2 = 0;
            int k = i;
            //查询由‘.’分开的相同级别的子字符串,并计算代表的数值大小
            while(k < len1 && version1[k] != '.') {
                sv1 *= 10;
                sv1 += (version1[k] - '0');
                k++;
            }
            i = k + 1;
            k = j;
            while(k < len2 && version2[k] != '.') {
                sv2 *= 10;
                sv2 += (version2[k] - '0');
                k++;
            }
            j = k + 1;
            if(sv1 < sv2) {
                ans = -1;
                break;
            }         
            else if(sv1 > sv2) {
                ans = 1;
                break;
            }
        }
        
        return ans;
    }
};

 

posted @ 2019-05-30 20:03  你好哇傻小妞  阅读(122)  评论(0编辑  收藏  举报