题解 | #比较版本号#
比较版本号
https://www.nowcoder.com/practice/2b317e02f14247a49ffdbdba315459e7
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 比较版本号 * @param version1 string字符串 * @param version2 string字符串 * @return int整型 */ public int compare (String version1, String version2) { if (version1.equals(" ") && version2.equals(" ")) return 0; String c = "."; int num1 = 0, num2 = 0; int dot1 = 0, dot2 = 0; int s1 = version1.length(); int s2 = version2.length(); if (version1.contains(c)) { for (int i = 0 ; i < s1; i++) { if (version1.charAt(i) == '.') { dot1 = i; break; } } } else { dot1 = version1.length(); } if (version2.contains(c)) { for (int i = 0 ; i < s2; i++) { if (version2.charAt(i) == '.') { dot2 = i; break; } } } else { dot2 = version2.length(); } int com1 = 0, com2 = 0; String string1 = new String(version1.substring(num1, dot1)); String string2 = new String(version2.substring(num2, dot2)); if (!string1.equals(" ")) com1 = Integer.parseInt(string1); else { com1 = 0; } if (!string2.equals(" ")) com2 = Integer.parseInt(string2); else { com2 = 0; } if (com1 > com2) return 1; else if (com1 < com2) { return -1; } return compare(dot1 < version1.length() ? version1.substring(dot1 + 1, version1.length()) : " ", dot2 < version2.length() ? version2.substring(dot2 + 1, version2.length()) : " "); } }