zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    文件和数组的排序
    批量删除文档中的注释和空行
    strcat()的编写
    OpenGL鼠标旋转图像
    c++对文件操作的支持(二)
    汉字的16进制存储
    启动程序的c++方法
    HDU 2199 Can you solve this equation? 二分
    HDU 2899 Strange fuction 二分
    HDU 1233 还是畅通工程 最小生成树
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9485136.html
Copyright © 2011-2022 走看看