博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Compare Version Numbers
阅读量:5077 次
发布时间:2019-06-12

本文共 3015 字,大约阅读时间需要 10 分钟。

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

Credits:

Special thanks to  for adding this problem and creating all test cases.

 

Hide Tags
 
 
 
分析:将字符串中的每个数字提取出来,保存到数组中,然后逐个比较数组各个元素。
 
注意:“1” 和 “1.0” 以及“1.0.0” 是相同的,需要单独处理一下。。

 

也快参考 http://www.cnblogs.com/grandyang/p/4244123.html 

 

class Solution {    private:        int string2Int(const string& str)        {            if(str.size() == 0)                return 0;            int rtn = 0;            for(int i = 0; i < str.size(); i++)            {                rtn = rtn*10 + (str[i] - '0');            }            return rtn;        }        vector
string2Ints(const string& str) { vector
rtn; if(str.size() == 0) return rtn; int size = str.size(); int left = 0; int tmp; for(int i = 0; i < size; i++) { if(str[i] == '.') { tmp = string2Int(str.substr(left, i - left )); rtn.push_back(tmp); left = i + 1; } } tmp = string2Int(str.substr(left, size + 1 - left )); rtn.push_back(tmp); return rtn; } public: int compareVersion(string version1, string version2) { if(version1 == version2) return false; vector
rtn1 = string2Ints(version1); vector
rtn2 = string2Ints(version2); //printVector(rtn1); //printVector(rtn2); int size = min(rtn1.size(), rtn2.size()); for(int i = 0; i < size; i++) { if(rtn1[i] > rtn2[i] ) return 1; else if(rtn1[i] < rtn2[i] ) return -1; } if(rtn1.size() == rtn2.size()) return 0; else if(rtn1.size() > rtn2.size()) { for(int i = size; i < rtn1.size(); i++) { if(rtn1[i] != 0) return 1; } return 0;//all is zero } else //if(rtn1.size() < rtn2.size()) { for(int i = size; i < rtn2.size(); i++) { if(rtn2[i] != 0) return -1; } return 0;//all is zero } }};

 

转载于:https://www.cnblogs.com/diegodu/p/4635269.html

你可能感兴趣的文章
常量优化机制
查看>>
UIVIEW圆角和边框设置
查看>>
pcb过孔盖油
查看>>
两天笔记
查看>>
对TCP/IP协议的一些看法(10):TCP协议(2)
查看>>
IE下window.onresize被多次执行的解决
查看>>
多选框全选js
查看>>
Python学习第四天
查看>>
121. Best Time to Buy and Sell Stock(动态规划)
查看>>
oracle 修改表的sql语句
查看>>
OpenNI2安装
查看>>
[Leetcode] Valid Parentheses
查看>>
[8.1] Triple Step
查看>>
JAVA网络编程
查看>>
《DSP using MATLAB》示例Example7.4
查看>>
tcp断开过程
查看>>
手机工作平台的搭建
查看>>
[CareerCup] 9.8 Represent N Cents 组成N分钱
查看>>
POJ - 1330 Nearest Common Ancestors(dfs+ST在线算法|LCA倍增法)
查看>>
MD5,sha1加密工具类
查看>>