LeetCode 165 - Compare Version Numbers


[leetcode] Compare Version Numbers - 追梦船的专栏 - 博客频道 - CSDN.NET
Compare two version numbers version1 and version1.
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
从高位到低位递归解决。 注意特殊case (1,1.0);

X. Constant Space
http://www.jyuan92.com/blog/leetcode-compare-version-numbers/
https://leetcode.com/problems/compare-version-numbers/discuss/50788/My-JAVA-solution-without-split
https://leetcode.com/problems/compare-version-numbers/discuss/50767/My-2ms-easy-solution-with-CC%2B%2B
Rather than use two String[], we can handle this in constant space.
public int compareVersion2(String version1, String version2) {
   if (null == version1 || null == version2) {
       return 0;
   }
   if (version1.equals(version2)) {
       return 0;
   }
   int aLength = version1.length();
   int bLength = version2.length();
   int i = 0;
   int j = 0;
   while (i < aLength || j < bLength) {
       int aTemp = 0;
       int bTemp = 0;
       while (i < aLength && version1.charAt(i) != '.') {
           aTemp  = aTemp * 10 + version1.charAt(i) - '0';
           i++;
       }
       while (j < bLength && version2.charAt(j) != '.') {
           bTemp  = bTemp * 10 + version2.charAt(j) - '0';
           j++;
       }
       if (aTemp < bTemp) {
           return -1;
       }
       if (aTemp > bTemp) {
           return 1;
       }
       i++;
       j++;
   }
   return 0;
}
https://leetcode.com/discuss/20675/solution-using-two-pointer-java
Keep two pointer to get the substring until next "." or the end. Then compare the substring parsed. If one string is ended, assign 0 value for comparing.
public int compareVersion(String version1, String version2) { int i = 0,j = 0; int pre1 = i, pre2 = j; while(i < version1.length() || j < version2.length()){ while(i < version1.length()){ if(version1.charAt(i)=='.') break; i++; } while(j < version2.length()){ if(version2.charAt(j)=='.') break; j++; } int int1 = pre1 < i?Integer.parseInt(version1.substring(pre1,i)):0; int int2 = pre2 < j?Integer.parseInt(version2.substring(pre2,j)):0; if(int1 > int2) return 1; else if(int1 < int2) return -1; pre1 = ++i; pre2 = ++j; } return 0; }
X>
https://leetcode.com/problems/compare-version-numbers/discuss/50774/Accepted-small-Java-solution.
This code assumes that next level is zero if no mo levels in shorter version number. And than compare levels.
public int compareVersion(String version1, String version2) {
    String[] levels1 = version1.split("\\.");
    String[] levels2 = version2.split("\\.");
    
    int length = Math.max(levels1.length, levels2.length);
    for (int i=0; i<length; i++) {
     Integer v1 = i < levels1.length ? Integer.parseInt(levels1[i]) : 0;
     Integer v2 = i < levels2.length ? Integer.parseInt(levels2[i]) : 0;
     int compare = v1.compareTo(v2);
     if (compare != 0) {
      return compare;
     }
    }
    
    return 0;
}
https://segmentfault.com/a/1190000003803133
  1. 1.01是一个版本,意味即使长度不一样,也要检查后面是否都是0
  2. 1.15要大于1.5,因为前者是第15个子版本,而后者是第5个
最简单的方法就是用split方法按照.分割,然后比对相应的每一个子串。
因为split方法输入的是一个正则表达式所以不能直接用.,而是要用\.,而java的\要转义,所有要用\\.
    public int compareVersion(String version1, String version2) {
        // 按照.进行分割
        String[] v1 = version1.split("\\.");
        String[] v2 = version2.split("\\.");
        int i = 0;
        // 比对相应的子串
        for(; i < v1.length && i < v2.length; i++){
            int val1 = Integer.parseInt(v1[i]);
            int val2 = Integer.parseInt(v2[i]);
            if(val1 < val2) return -1;
            if(val1 > val2) return 1;
        }
        // 如果某个版本号更长,判断其多余部分是否是0,如果不是0,则较长的较大,否则是一样的。
        if(v2.length > v1.length){
            for(; i < v2.length; i++){
                int val = Integer.parseInt(v2[i]);
                if(val != 0) return -1;
            }
        } else if(v1.length > v2.length){
            for(; i < v1.length; i++){
                int val = Integer.parseInt(v1[i]);
                if(val != 0) return 1;
            }
        }
        return 0;
    }
http://yuanhsh.iteye.com/blog/2175676
注意各种edge case,比如:0.0.1, 0.1 和 1.0, 1
  1. public int compareVersion(String version1, String version2) {  
  2.     String[] v1 = version1.split("\\.");  
  3.     String[] v2 = version2.split("\\.");  
  4.     int maxLength = Math.max(v1.length, v2.length);  
  5.     for(int i=0; i<maxLength; i++) {  
  6.         Integer a = i<v1.length ? Integer.parseInt(v1[i]) : 0;  
  7.         Integer b = i<v2.length ? Integer.parseInt(v2[i]) : 0;  
  8.         int res = a.compareTo(b);  
  9.         if(res != 0return res;  
  10.     }  
  11.     return 0;  
  12. }  
http://www.programcreek.com/2014/03/leetcode-compare-version-numbers-java/

public int compareVersion(String version1, String version2) {
    String[] arr1 = version1.split("\\.");
    String[] arr2 = version2.split("\\.");
 
    int i=0;
    while(i<arr1.length || i<arr2.length){
        if(i<arr1.length && i<arr2.length){
            if(Integer.parseInt(arr1[i]) < Integer.parseInt(arr2[i])){
                return -1;
            }else if(Integer.parseInt(arr1[i]) > Integer.parseInt(arr2[i])){
                return 1;
            }
        } else if(i<arr1.length){
            if(Integer.parseInt(arr1[i]) != 0){
                return 1;
            }
        } else if(i<arr2.length){
           if(Integer.parseInt(arr2[i]) != 0){
                return -1;
            }
        }
 
        i++;
    }
 
    return 0;
}
http://www.zhuangjingyang.com/leetcode-compare-version-numbers/
   public  int compareVersion(String version1, String version2) {
     String[] v1 = version1.split("\\.");
     String[] v2 = version2.split("\\.");
     int i=0;
     for(;i<v1.length && i < v2.length;i++){
     int t  = compare(v1[i],v2[i]);
     if(t != 0)
     return t;
     }
    
     //if version1 is longer
     while(i<v1.length){
     if(Integer.parseInt(v1[i++])!=0)
     return 1;
     }
    
     //if version2 is longer
     while(i<v2.length){
     if(Integer.parseInt(v2[i++])!=0)
     return -1;
     }
    
     return 0;
     }
    
    public  int compare(String t1,String t2){
     int v1 = Integer.parseInt(t1);
     int v2 = Integer.parseInt(t2);
     return v1>v2?1:v1<v2?-1:0;
    }
  1. public int compareVersion(String version1, String version2) { //java  
  2.     if(version1.equals(version2))  
  3.         return 0;  
  4.           
  5.     int fversion1 , fversion2;  
  6.     String sversion1,sversion2;  
  7.     if(version1.contains(".")){  
  8.         int pos = version1.indexOf(".");  
  9.         fversion1 = Integer.valueOf(version1.substring(0,pos));  
  10.         sversion1 = version1.substring(pos+1,version1.length());  
  11.     }  
  12.     else {  
  13.         fversion1 = Integer.valueOf(version1);  
  14.         sversion1 = "0";  
  15.     }  
  16.       
  17.     if(version2.contains(".")){  
  18.         int pos = version2.indexOf(".");  
  19.         fversion2 = Integer.valueOf(version2.substring(0,pos));  
  20.         sversion2 = version2.substring(pos+1,version2.length());  
  21.     }  
  22.     else {  
  23.         fversion2 = Integer.valueOf(version2);  
  24.         sversion2 = "0";  
  25.     }  
  26.       
  27.     if(fversion1 > fversion2)  
  28.         return 1;  
  29.     else if(fversion1 < fversion2)  
  30.         return -1;  
  31.     else return compareVersion(sversion1, sversion2);  
  32. }  
http://blog.csdn.net/lavorange/article/details/42048687
算法思路:1.首先考虑将两个字符串version1和version2进行切分,因为可能会出现这样的测试用例"1.0.1",有多个点。

2.将按照"."分割之后的数字放到一个容器vector里面或者一个数组里面就行了。

3.然后依次进行比较。有一点需要注意的是,有类似的用例"1.0.0"和"1"其实是相等的,因此,要将容器或者数组中的后缀0去掉,那么比较的时候就没有什么顾虑了。
  1.     void split_string(const char *str , vector<int> &v)     
  2.     {  
  3.         char *buf = new char[ strlen(str) + 1 ];  
  4.         strcpy(buf,str);  
  5.         char *p = strtok(buf,".");  
  6.         while( p!=NULL )  
  7.         {  
  8.             v.push_back( atoi(p) ) ;  
  9.             p = strtok(NULL,".");  
  10.         }  
  11.     }  
  12.       
  13.     //compare two version  
  14.     int compareVersion(string version1, string version2)   
  15.     {  
  16.         const char *str1 = version1.c_str();  
  17.         const char *str2 = version2.c_str();  
  18.           
  19.         split_string(str1,v1);  
  20.         split_string(str2,v2);  
  21.           
  22.         return judge();  
  23.     }  
  24.       
  25.     int judge()  
  26.     {  
  27.         //prune the suffix zero : 1.0 == 1  
  28.         while( v1.size()!=0 && v1[v1.size()-1]==0 )  
  29.         {  
  30.             v1.pop_back();         
  31.         }  
  32.          while( v2.size()!=0 && v2[v2.size()-1]==0 )  
  33.         {  
  34.             v2.pop_back();         
  35.         }  
  36.           
  37.         int size = min( v1.size(),v2.size() );  
  38.         int i;  
  39.         for(i=0;i<size;i++)  
  40.         {  
  41.             if( v1[i]>v2[i] )   return 1;  
  42.             else if( v1[i]<v2[i] ) return -1;  
  43.             else continue;  
  44.         }  
  45.           
  46.         if( v1.size() > v2.size() )       
  47.         {   
  48.               return 1;    
  49.         }  
  50.         else if( v1.size() < v2.size() ) return -1;  
  51.         else return 0;  
  52.           
  53.     }  
  54. }; 

https://leetcode.com/discuss/24078/simple-java-solution
What if the value of a subversion is larger than Integer. MAX_VALUE?
Some guys point to MAX_VALUE problem, I think it is a good point. I revise my solution to solve this problem and without using compareTo().
The basic idea is same.
strCmp() method is used to compare two tokens without parsing to int. The idea of this method is very very similar: fill zeros if the length is not consistent.
for example: "001" vs. "1" --> "001" vs. "001"
public int compareVersion(String version1, String version2) { String ver1[] = version1.split("\\."); String ver2[] = version2.split("\\."); int len = ver1.length > ver2.length ? ver1.length : ver2.length; for (int i = 0; i < len; i++) { String v1 = i < ver1.length ? ver1[i] : "0"; String v2 = i < ver2.length ? ver2[i] : "0"; int compare = strCmp(v1, v2); if (compare != 0) return compare; } return 0; } public int strCmp(String s1, String s2) { int len = s1.length() > s2.length() ? s1.length() : s2.length(); for (int i = 0; i < len; i++) { char v1 = i + s1.length() < len ? '0' : s1.charAt(i - len + s1.length()); char v2 = i + s2.length() < len ? '0' : s2.charAt(i - len + s2.length()); if (v1 > v2) return 1; if (v1 < v2) return -1; } return 0; }
http://www.geeksforgeeks.org/compare-two-version-numbers/
If we have more than two version then below versionCompare method can be used as cmp method of sort method, which will sort all versions according to specified comparison.
int versionCompare(string v1, string v2)
{
    //  vnum stores each numeric part of version
    int vnum1 = 0, vnum2 = 0;
    //  loop untill both string are processed
    for (int i=0,j=0; (i<v1.length() || j<v2.length()); )
    {
        //  storing numeric part of version 1 in vnum1
        while (i < v1.length() && v1[i] != '.')
        {
            vnum1 = vnum1 * 10 + (v1[i] - '0');
            i++;
        }
        //  storing numeric part of version 2 in vnum2
        while (j < v2.length() && v2[j] != '.')
        {
            vnum2 = vnum2 * 10 + (v2[j] - '0');
            j++;
        }
        if (vnum1 > vnum2)
            return 1;
        if (vnum2 > vnum1)
            return -1;
        //  if equal, reset variables and go for next numeric
        // part
        vnum1 = vnum2 = 0;
        i++;
        j++;
    }
    return 0;
}
Read full article from [leetcode] Compare Version Numbers - 追梦船的专栏 - 博客频道 - CSDN.NET

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts