思路:依然是左边补0,但不借用compareTo,自己处理compare逻辑
// @Title: 比较版本号 (Compare Version Numbers)
// @Author: qisiii
// @Date: 2024-10-11 20:34:56
// @Runtime: 1 ms
// @Memory: 40.8 MB
// @comment: 依然是左边补0,但不借用compareTo,自己处理compare逻辑
// @flag: GREEN
class Solution {
public int compareVersion(String version1, String version2) {
String[] str1 = version1.split("\\.");
String[] str2 = version2.split("\\.");
int index = 0;
while (index < str1.length || index < str2.length) {
String s1 = index >= str1.length ? "" : str1[index];
String s2 = index >= str2.length ? "" : str2[index];
int result = compare(s1,s2);
if (result == 0) {
index++;
} else {
return result;
}
}
return 0;
}
private int compare(String s1,String s2){
if (s1.length() > s2.length()) {
s2 = addZero(s1.length() - s2.length())+s2;
} else if (s1.length() < s2.length()) {
s1 = addZero(s2.length() - s1.length())+s1;
}
int index=0;
while(index<s1.length()){
char c1=s1.charAt(index);
char c2=s2.charAt(index);
if(c1>c2){
return 1;
}else if(c1<c2){
return -1;
}else{
index++;
}
}
return 0;
}
private String addZero(int length) {
StringBuilder str = new StringBuilder();
while (length > 0) {
str.append('0');
length--;
}
return str.toString();
}
}
思路:不足的往前补0,借用compareTo,返回值是差值
// @Title: 比较版本号 (Compare Version Numbers)
// @Author: qisiii
// @Date: 2024-10-11 20:24:56
// @Runtime: 1 ms
// @Memory: 40.6 MB
// @comment: 不足的往前补0,借用compareTo,返回值是差值
// @flag: BLUE
class Solution {
public int compareVersion(String version1, String version2) {
String[] str1 = version1.split("\\.");
String[] str2 = version2.split("\\.");
int index = 0;
while (index < str1.length || index < str2.length) {
String s1 = index >= str1.length ? "" : str1[index];
String s2 = index >= str2.length ? "" : str2[index];
if (s1.length() > s2.length()) {
s2 = addZero(s1.length() - s2.length())+s2;
} else if (s1.length() < s2.length()) {
s1 = addZero(s2.length() - s1.length())+s1;
}
int result = s1.compareTo(s2);
if (result == 0) {
index++;
} else {
return result>0?1:-1;
}
}
return 0;
}
private String addZero(int length) {
StringBuilder str = new StringBuilder();
while (length > 0) {
str.append('0');
length--;
}
return str.toString();
}
}