zoukankan      html  css  js  c++  java
  • 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;
    	    }
    	  }
    
  • 相关阅读:
    node之body-parser的使用
    node解决跨域问题
    node之post提交上传
    HDU 6397(容斥原理)
    HDU 3374(最小最大表示法+KMP)
    HDU 6396(优先队列+思维)
    HDU 6395(矩阵快速幂)
    HDU 6370(并查集)
    HDU 6356(线段树)
    HDU 6354(计算几何)
  • 原文地址:https://www.cnblogs.com/cznczai/p/11320472.html
Copyright © 2011-2022 走看看