【LeetCode】#165比较版本号(Compare Version Numbers)
题目描述
比较两个版本号 version1 和 version2。
如果 version1 > version2 返回 1,如果 version1 < version2 返回 -1, 除此之外返回 0。
你可以假设版本字符串非空,并且只包含数字和 . 字符。
. 字符不代表小数点,而是用于分隔数字序列。
例如,2.5 不是“两个半”,也不是“差一半到三”,而是第二版中的第五个小版本。
示例
示例 1:
输入: version1 = “0.1”, version2 = “1.1”
输出: -1
示例 2:
输入: version1 = “1.0.1”, version2 = “1”
输出: 1
示例 3:
输入: version1 = “7.5.2.4”, version2 = “7.5.3”
输出: -1
Description
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
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
解法
class Solution {
public int compareVersion(String version1, String version2) {
if(version1.equals(version2)){
return 0;
}
String[] str1 = version1.split("\\.");
String[] str2 = version2.split("\\.");
int res = 0;
if(str1.length<str2.length){
res = -1;
for(int i=0; i<str1.length; i++){
if(Integer.parseInt(str1[i])>Integer.parseInt(str2[i])){
res = 1;
break;
}else if(Integer.parseInt(str1[i])<Integer.parseInt(str2[i])){
res = -1;
break;
}
}
for(int i=str1.length; i<str2.length; i++){
if(Integer.parseInt(str2[i])!=0){
break;
}
if(i==str2.length-1){
res = 0;
}
}
}else if(str2.length<str1.length){
res = 1;
for(int i=0; i<str2.length; i++){
if(Integer.parseInt(str1[i])>Integer.parseInt(str2[i])){
res = 1;
break;
}else if(Integer.parseInt(str1[i])<Integer.parseInt(str2[i])){
res = -1;
break;
}
}
for(int i=str2.length; i<str1.length; i++){
if(Integer.parseInt(str1[i])!=0){
break;
}
if(i==str1.length-1){
res = 0;
}
}
}else{
res = 0;
for(int i=0; i<str1.length; i++){
if(Integer.parseInt(str1[i])>Integer.parseInt(str2[i])){
res = 1;
break;
}else if(Integer.parseInt(str1[i])<Integer.parseInt(str2[i])){
res = -1;
break;
}
}
}
return res;
}
}