zoukankan      html  css  js  c++  java
  • Leetcode 165. Compare Version Numbers

    Compare two version numbers version1 and version2.
    If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.

    You may assume that the version strings are non-empty and contain only digits and the . character.
    The . character does not represent a decimal point and is used to separate number sequences.
    For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

    Here is an example of version numbers ordering:

    0.1 < 1.1 < 1.2 < 13.37

    Next challenges: Text Justification Edit Distance Longest Uncommon Subsequence I

    思路:按照"."先将version1和version2分别分割为字符串数组,然后一段一段比较,注意对于当前的一段可能会有前缀0的出现,比如"001"和"1"。另外将每一段转换为整数来处理是不可行的,比如"2.10000000000000000000000000000"和"2.1"。

    代码:

     1 public int compareVersion(String version1, String version2) {
     2         String[] array1 = version1.split("\.");
     3         String[] array2 = version2.split("\.");
     4         int time = Math.max(array1.length, array2.length);
     5         for(int i = 0; i < time; i++) {
     6             String s1 = i < array1.length ? array1[i] : "0";
     7             String s2 = i < array2.length ? array2[i] : "0";
     8             //去掉前缀0
     9             int j = 0;
    10             while(j < s1.length() - 1 && s1.charAt(j) == '0') j++;
    11             if(j > 0) s1 = s1.substring(j);
    12             j = 0;
    13             while(j < s2.length() - 1 && s2.charAt(j) == '0') j++;
    14             if(j > 0) s2 = s2.substring(j);
    15             
    16             if(s1.length() == s2.length()) {
    17                 for(int k = 0; k < s1.length() ; k++) {
    18                     if(s1.charAt(k) == s2.charAt(k)) continue;
    19                     return s1.charAt(k) > s2.charAt(k) ? 1 : -1;                    
    20                 }
    21             }else{
    22                 return s1.length() > s2.length() ? 1 : -1;
    23             }
    24         }
    25         return 0;
    26     }
  • 相关阅读:
    [转载]小谈网络游戏同步
    [ASE][Daily Scrum]11.06
    [Proposal]Tank Battle——Infinite
    [proposal][app]Watch your time!
    [Proposal]Nano-Diary(纳日记)
    LaTeX中用BibTex管理参考文献
    matlab化简符号表达式
    placeholder颜色变化
    链接图片外边出现蓝框(IE8/IE9/IE10)
    图标排列
  • 原文地址:https://www.cnblogs.com/Deribs4/p/7223947.html
Copyright © 2011-2022 走看看