版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/86418869
我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/compare-version-numbers/description/
题目描述:
知识点:字符串
思路一:先分割再比较
时间复杂度是O(n),其中n为version1和version2中较长字符串的长度。空间复杂度是O(m),其中m为version1和version2分割得到的数字的数量。
JAVA代码:
public class Solution {
public int compareVersion(String version1, String version2) {
ArrayList<Integer> arrayList1 = changeToArray(version1);
ArrayList<Integer> arrayList2 = changeToArray(version2);
for(int i = 0; i < arrayList1.size() || i < arrayList2.size(); i++){
int num1 = 0, num2 = 0;
if(i < arrayList1.size() && i < arrayList2.size()){
num1 = arrayList1.get(i);
num2 = arrayList2.get(i);
}else if(i < arrayList1.size() && i >= arrayList2.size()){
num1 = arrayList1.get(i);
}else if(i >= arrayList1.size() && i < arrayList2.size()){
num2 = arrayList2.get(i);
}
if(num1 > num2){
return 1;
}else if(num1 < num2){
return -1;
}
}
return 0;
}
private ArrayList<Integer> changeToArray(String version){
ArrayList<Integer> arrayList = new ArrayList<>();
String[] strings = version.split("\\.");
for(String string : strings){
arrayList.add(Integer.parseInt(string));
}
return arrayList;
}
}
LeetCode解题报告:
思路二:边分割边比较
时间复杂度是O(n),其中n为version1和version2中较长字符串的长度。空间复杂度是O(1)。
JAVA代码:
public class Solution {
public int compareVersion(String version1, String version2) {
int index1 = 0, index2 = 0;
while(index1 < version1.length() || index2 < version2.length()){
int num1 = 0, num2 = 0;
if(index1 < version1.length() && index2 < version2.length()){
num1 = getNextNum(version1, index1);
num2 = getNextNum(version2, index2);
int temp1 = version1.substring(index1).indexOf(".");
if(temp1 != -1) {
index1 += temp1 + 1;
}else{
index1 = version1.length();
}
int temp2 = version2.substring(index2).indexOf(".");
if(temp2 != -1) {
index2 += temp2 + 1;
}else{
index2 = version2.length();
}
}else if(index1 < version1.length() && index2 >= version2.length()){
num1 = getNextNum(version1, index1);
int temp1 = version1.substring(index1).indexOf(".");
if(temp1 != -1) {
index1 += temp1 + 1;
}else{
index1 = version1.length();
}
}else if(index1 >= version1.length() && index2 < version2.length()){
num2 = getNextNum(version2, index2);
int temp2 = version2.substring(index2).indexOf(".");
if(temp2 != -1) {
index2 += temp2 + 1;
}else{
index2 = version2.length();
}
}
if(num1 > num2){
return 1;
}else if(num1 < num2){
return -1;
}
}
return 0;
}
private int getNextNum(String version, int index){
if(version.substring(index).indexOf(".") == -1){
return Integer.parseInt(version.substring(index));
}
return Integer.parseInt(version.substring(index, version.substring(index).indexOf(".") + index));
}
}
LeetCode解题报告: