本文主要是介绍LeetCode 题解(212) : 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
题解:
先以“.” split 然后按顺序由前往后比较。当短的结束后需要判断长的是否只包含0.
C++需要自己写split函数。Java版注意以"."为分割时需要添加转移字符"\\."
C++版:
class Solution {
public:int compareVersion(string version1, string version2) {vector<string> v1 = split(version1, '.');vector<string> v2 = split(version2, '.');int i = 0;while(i < min(v1.size(), v2.size())) {if(stoi(v1[i]) > stoi(v2[i]))return 1;if(stoi(v1[i]) < stoi(v2[i]))return -1;i++;}if(v1.size() > v2.size()) {while(i < v1.size()) {if(stoi(v1[i]) != 0)return 1;i++;}} else if(v1.size() < v2.size()) {while(i < v2.size()) {if(stoi(v2[i]) != 0)return -1;i++;}}return 0;}vector<string> split(const string &s, char delim) {stringstream ss(s);string item;vector<string> tokens;while (getline(ss, item, delim)) {tokens.push_back(item);}return tokens;}
};
Java版:
public class Solution {public int compareVersion(String version1, String version2) {String[] v1 = version1.split("\\.");String[] v2 = version2.split("\\.");int i = 0;while(i < Math.min(v1.length, v2.length)) {if(Integer.parseInt(v1[i]) > Integer.parseInt(v2[i]))return 1;else if(Integer.parseInt(v1[i]) < Integer.parseInt(v2[i]))return -1;i++;}if(v1.length > v2.length) {while(i < v1.length) {if(Integer.parseInt(v1[i]) != 0)return 1;i++;}} else if(v2.length > v1.length) {while(i < v2.length) {if(Integer.parseInt(v2[i]) != 0)return -1;i++;}}return 0;}
}
Python版:
class Solution(object):def compareVersion(self, version1, version2):""":type version1: str:type version2: str:rtype: int"""v1, v2 = version1.split("."), version2.split(".")i = 0while i < min(len(v1), len(v2)):if int(v1[i]) > int(v2[i]):return 1elif int(v1[i]) < int(v2[i]):return -1i += 1if len(v1) > len(v2):while i < len(v1):if int(v1[i]) != 0:return 1i += 1elif len(v2) > len(v1):while i < len(v2):if int(v2[i]) != 0:return -1i += 1return 0
这篇关于LeetCode 题解(212) : Compare Version Numbers的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!