leetcode Compare Version Numbers

来源:互联网 发布:导弹牵引车知乎 编辑:程序博客网 时间:2024/06/03 07:16

题目

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.

依次比较版本号,就是怎样获得版本号的问题。可以直接用string.split("\\.")

也可以像下边这样。

int temp1=prei<i?Integer.parseInt(version1.substring(prei,i)):0; 这是算法里我认为比较有意思的地方。

public class Solution {
    public int compareVersion(String version1, String version2) {
    int i=0;
int j=0;
int prei=0;
int prej=0;
while(i<version1.length()||j<version2.length()){
while(i<version1.length()){
if(version1.charAt(i)=='.')
break;
i++;
}
while(j<version2.length()){
if(version2.charAt(j)=='.'){
break;
}
j++;
}

int temp1=prei<i?Integer.parseInt(version1.substring(prei,i)):0; 
int temp2=prej<j?Integer.parseInt(version2.substring(prej,j)):0;
if(temp1>temp2){
return 1;
}else if(temp1<temp2){
return -1;
}
prei=++i;
prej=++j;
}

return 0;
    }
}

0 0
原创粉丝点击