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;
    	    }
    	  }
    
  • 相关阅读:
    new in swift
    Mac Git [remote rejected] master -> master (pre-receive hook declined) 解决方案
    Mac git 代码的Add 以及提交
    swift storyboard 跳转的2 种方式
    iOS 常用指令(svn cocoa pod)
    java面试题(晨星)
    谈Spring的理解
    软件产品开发文档大纲
    商城项目要点
    金蝶面试小记
  • 原文地址:https://www.cnblogs.com/cznczai/p/11320472.html
Copyright © 2011-2022 走看看