第36题 Compare Version Numbers
来源:互联网 发布:linux创建文件夹进入 编辑:程序博客网 时间:2024/05/16 12:00
Compare two version numbers version1 and version1.
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 @ts for adding this problem and creating all test cases.
Solution in Java:
public class Solution { public int compareVersion(String version1, String version2) { String[] v1 = version1.split("\\."); String[] v2 = version2.split("\\."); for(int i=0; i<Math.min(v1.length, v2.length); i++){ if(Integer.parseInt(v1[i])<Integer.parseInt(v2[i])) return -1; else if(Integer.parseInt(v1[i])>Integer.parseInt(v2[i])) return 1; } boolean zero=true; if(v1.length<v2.length){ for(int i=v1.length; i<v2.length; i++) zero = zero&(Integer.parseInt(v2[i])==0); if(!zero) return -1; } if(v1.length>v2.length){ for(int i=v2.length; i<v1.length; i++) zero = zero&(Integer.parseInt(v1[i])==0); if(!zero) return 1; } return 0; }}
Note:
用“.”分割字符串时,注意需要转义成“\\.”,其中“\”自身还需要转义一次。
version“1.0” version“1”和version“1.0.0.0”是相等的,所以当两个version长度不一样时,需要检查长的一方后面几个部分是否都为0,如果是则返回0,相等。
Solution in C++:
class Solution {public: int compareVersion(string version1, string version2) { int ptr1 = 0, ptr2 = 0; int val1 = 0, val2=0; while(ptr1<version1.size()||ptr2<version2.size()){ while(ptr1<version1.size()&&version1[ptr1]!='.'){ val1 = val1*10 + (version1[ptr1]-'0'); ptr1++; } while(ptr2<version2.size()&&version2[ptr2]!='.'){ val2 = val2*10 + (version2[ptr2]-'0'); ptr2++; } if(val1>val2) return 1; if(val1<val2) return -1; val1=0; val2=0; ptr1++; ptr2++; } return 0; }};
Note: 不关心格式,val1和val2初值赋为0,只关心该段内值的大小。
0 0
- 第36题 Compare Version Numbers
- LeetCode 第 165 题(Compare Version Numbers)
- Easy 165题 Compare Version Numbers
- Leetcode Compare Version Numbers
- Compare Version Numbers
- [leetcode] Compare Version Numbers
- Compare Version Numbers
- Compare Version Numbers
- [leetcode] Compare Version Numbers
- Compare Version Numbers
- Leetcode: Compare Version Numbers
- 【Leetcode】:Compare Version Numbers
- Compare Version Numbers (Java)
- 165 Compare Version Numbers
- leetcode:Compare Version Numbers
- [LeetCode]Compare Version Numbers
- [leetCode] Compare Version Numbers
- [leetcode] Compare Version Numbers
- Memo: Jquery 常忘语句
- 如何使用JAVA打印菱形(三)空心菱形基础上加上对角线
- 常见算法问题的分类
- 详解 $_SERVER 函数中QUERY_STRING和REQUEST_URI区别
- windows2008远程重启
- 第36题 Compare Version Numbers
- mysql中文乱码的一点理解
- 美女图片站的简单制作过程
- VC6.0打开文件以及向工程中添加文件时程序崩溃自动退出
- 【c++11】override(重写)与final(最终)
- _stdcall, _cdecl的用法与区别
- SQL Server自动生成拼音首字母!!!
- ios 退出app
- 一个问题,学习笔记