165. Compare Version Numbers
Posted cznczai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了165. Compare Version Numbers相关的知识,希望对你有一定的参考价值。
今天项目里遇到以"." 、""、“|”分割字符串,直接用"." 、""、“|”无法分割,因为"." 、""、“|”是特殊字符,需要转义,"\\." 、"\\"、“\\|”。
class Solution
public int compareVersion(String version1, String version2)
String[] arr1 = version1.split("\\\\.");
String[] arr2 = version2.split("\\\\.");
int n = arr1.length>arr2.length?arr1.length:arr2.length;
int temp1[] = new int [n];
int temp2[] = new int [n];
for(int i = 0 ; i < arr1.length ; i++)
temp1[i] = Integer.parseInt(arr1[i]);
for(int i = 0 ; i < arr2.length ; i++)
temp2[i] = Integer.parseInt(arr2[i]);
int flag = 0;
while(flag<n)
if(temp1[flag]<temp2[flag])
return -1;
else if(temp1[flag]>temp2[flag])
return 1;
flag++;
return 0;
精简~
class Solution
public int compareVersion(String s1, String s2)
int i = 0 ;
int j = 0 ;
while( i < s1.length() || j < s2.length())
int x = i ;
int y = j ;
while(x<s1.length()&&s1.charAt(x)!='.')x++;
while(y<s2.length()&&s2.charAt(y)!='.')y++;
int a = i==x?0:Integer.valueOf(s1.substring(i, x));
int b = j==y?0:Integer.valueOf(s2.substring(j, y));
if(a>b)return 1;
else if(a<b)return -1;
i = x+1;
j = y+1;
return 0;
以上是关于165. Compare Version Numbers的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 165. Compare Version Numbers
[LC] 165. Compare Version Numbers
Leetcode 165. Compare Version Numbers
165. Compare Version Numbers - LeetCode