leetcode165---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.

Here is an example of version numbers ordering:

0.1 < 1.1 < 1.2 < 13.37

就是比较“版本号”大小,给定的版本号version1和version2是字符串类型的,当version1>version2的时候,返回1,小于返回-1,相等返回0。

问题求解:

先分别将version1、version2字符串按’.’分割成多个子串,从前往后,前面的子串大小决定整个串的大小,即如果相等位置子串不等,则当version1>version2的时候,返回1,小于返回-1;如果全部子串都相等,则返回0.

class Solution {
public:
    int compareVersion(string version1, string version2) {
        int v1=0, v2=0;
        int n1=version1.size(), n2=version2.size();
        while(v1<n1 || v2<n2)
        {
            string str1="";
            string str2="";
            while(version1[v1] != '.' && v1<n1)
            {//按.截取字符串1的每一段
                str1 += version1[v1];
                ++v1;
            }
            while(version2[v2] != '.' && v2<n2)
            {//按.截取字符串2的每一段
                str2 += version2[v2];
                ++v2;
            }
            if(str1 == "") str1="0";//处理空的情况,对应大小为0
            if(str2 == "") str2="0";

            int i1=stoi(str1), i2=stoi(str2);
            if(i1 != i2)
            {
                return i1>i2?1:-1;
            }
            //i1==i2的情况,将两字符串索引后移,判断后面情况
            ++v1;
            ++v2;
        }
        return 0;
    }
};

你可能感兴趣的:(LeetCode)