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.
思路:
简单的数学推导而已,就是需要考虑的case比较多
我的代码:
public class Solution { public int compareVersion(String version1, String version2) { if(version1 == null && version2 == null) return 0; if(version1 == null) return -1; if(version2 == null) return 1; String[] ones = version1.split("\."); String[] twos = version2.split("\."); int i = 0; for(; i < ones.length && i < twos.length; i++) { int one = Integer.valueOf(ones[i]); int two = Integer.valueOf(twos[i]); if(one == two) continue; if(one > two) return 1; if(one < two) return -1; } while(i < ones.length) { int one = Integer.valueOf(ones[i]); if(one != 0) return 1; i++; } while(i < twos.length) { int two = Integer.valueOf(twos[i]); if(two != 0) return -1; i++; } return 0; } }
他人代码:
public class Solution { public int compareVersion(String version1, String version2) { String[] v1 = version1.split("\."); String[] v2 = version2.split("\."); int longest = v1.length > v2.length? v1.length: v2.length; for(int i=0; i<longest; i++) { int ver1 = i<v1.length? Integer.parseInt(v1[i]): 0; int ver2 = i<v2.length? Integer.parseInt(v2[i]): 0; if(ver1> ver2) return 1; if(ver1 < ver2) return -1; } return 0; } }
学习之处:
- 思路和方法都不难,就是需要考虑到的情况有点多,需要考虑仔细啦
- 他人的代码真简洁,简洁来源于int ver1 = i<v1.length? Integer.parseInt(v1[i]): 0;好好学习一下下。
- 让我联想到了Comparator 接口,接口的使用方法,如下代码所示,另外假如A的值大于B,你返回1。这样调用Collections.sort()方法就是升序;假如A的值大于B,你返回-1。这样调用Collections.sort()方法就是降序。
public class StringComparator implements Comparator<String>{ @Override public int compare(String A, String B) { return 0; } }