https://leetcode.com/problems/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
解题思路:
这种题目,面试的时候应该先问,version可能有多个'.'吗? 还要再问,version里可能有某一部分为0吗?或者结尾连续都是0,比如13.1.0.0.0?否则只能埋着头写程序。
事实证明,这两种情况是都会有的,加入到考虑里也不难。我倒是怀疑这题考得是如何实现split()方法还是怎么的。
提前判断好两个split数组的大小,也可以做。
public class Solution { public int compareVersion(String version1, String version2) { String[] version1SPlit = version1.split("\\."); String[] version2SPlit = version2.split("\\."); int i = 0; while(i < version1SPlit.length && i < version2SPlit.length){ if(Integer.parseInt(version1SPlit[i]) > Integer.parseInt(version2SPlit[i])){ return 1; } if(Integer.parseInt(version1SPlit[i]) < Integer.parseInt(version2SPlit[i])){ return -1; } i++; } if(i == version1SPlit.length && i == version2SPlit.length){ return 0; }else if(i == version1SPlit.length){ for(; i < version2SPlit.length; i++){ if(Integer.parseInt(version2SPlit[i]) > 0){ return -1; } } return 0; }else{ for(; i < version1SPlit.length; i++){ if(Integer.parseInt(version1SPlit[i]) > 0){ return 1; } } return 0; } } }