题解 | #比较版本号#
比较版本号
http://www.nowcoder.com/practice/2b317e02f14247a49ffdbdba315459e7
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 比较版本号
* @param version1 string字符串
* @param version2 string字符串
* @return int整型
*/
public int compare (String str1, String str2) {
// write code here
String [] str1s = str1.split("\\.");
String [] str2s = str2.split("\\.");
for(int i =0;i<Math.max(str1s.length,str2s.length);i++) {
String i1 = i>=str1s.length?"0":str1s[i];
String i2 = i>=str2s.length?"0":str2s[i];
int compare = compareTo(i1,removeZero(i1),i2,removeZero(i2));
if(compare!=0) {
return compare;
}
}
return 0;
}
int compareTo(String str1,int index1,String str2,int index2) {
int len1 = str1.length()-index1;
int len2 = str2.length()-index2;
if(len1!=len2) {
return len1>len2?1:-1;
} else {
for(int i =0;i<len1;i++) {
char c1 = str1.charAt(i+index1);
char c2 = str2.charAt(i+index2);
if(c1!=c2) {
return c1>c2?1:-1;
}
}
}
return 0;
}
int removeZero(String str) {
int len = str.length(), i = 0;
while (i < len && str.charAt(i) == '0') {
i++;
}
return i;
}
}