今天项目里遇到以"." 、""、“|”分割字符串,直接用"." 、""、“|”无法分割,因为"." 、""、“|”是特殊字符,需要转义,"." 、""、“|”。
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; } }