首页 > 代码库 > leetcode Compare Version Numbers
leetcode Compare Version Numbers
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
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
题目还是简单的,但是要考虑很多情况。
我写的代码边写边调试,写的比较烂。
1 public class Solution { 2 public int compareVersion(String version1, String version2) { 3 String[] versionsOne=version1.split("\\."); 4 String[] versionsTwo=version2.split("\\."); 5 int oneLength=versionsOne.length; 6 int twoLength=versionsTwo.length; 7 int length=oneLength<twoLength?oneLength:twoLength; 8 9 for (int i = 0; i < length; i++) {10 while (versionsOne[i].startsWith("0")&&versionsOne[i].length()>1) {11 versionsOne[i]=versionsOne[i].substring(1);12 }13 while (versionsTwo[i].startsWith("0")&&versionsTwo[i].length()>1) {14 versionsTwo[i]=versionsTwo[i].substring(1);15 }16 if (versionsOne[i].length()>versionsTwo[i].length()) {17 return 1;18 }else if (versionsOne[i].length()<versionsTwo[i].length()) {19 return -1;20 }21 int l = versionsOne[i].length()<versionsTwo[i].length()?versionsOne[i].length():versionsTwo[i].length();22 for (int j = 0; j < l; j++) {23 int a=versionsOne[i].charAt(j);24 int b=versionsTwo[i].charAt(j);25 if (a>b) {26 return 1;27 }else if (a<b) {28 return -1;29 }30 }31 32 }33 if (oneLength>twoLength) {34 for (int i = twoLength; i < oneLength; i++) {35 for (int j = 0; j < versionsOne[i].length(); j++) {36 if (versionsOne[i].charAt(j)>‘0‘) {37 return 1;38 }39 }40 }41 }else if (oneLength<twoLength) {42 for (int i = oneLength; i < twoLength; i++) {43 for (int j = 0; j < versionsTwo[i].length(); j++) {44 if (versionsTwo[i].charAt(j)>‘0‘) {45 return -1;46 }47 }48 }49 }50 return 0;51 }52 }
leetcode Compare Version Numbers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。