Problem
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.
Example 1:
Input: version1 = "0.1", version2 = "1.1" Output: -1
Example 2:
Input: version1 = "1.0.1", version2 = "1" Output: 1
Example 3:
Input: version1 = "7.5.2.4", version2 = "7.5.3" Output: -1Note
https://stackoverflow.com/que...
Basically if you want to split a dot ".", the regex "." means "any character", so you need to escape the dot with two backsplashes.
class Solution { public int compareVersion(String version1, String version2) { String[] v1 = version1.split("."); String[] v2 = version2.split("."); int len = Math.max(v1.length, v2.length); for (int i = 0; i < len; i++) { Integer i1 = i < v1.length ? Integer.parseInt(v1[i]) : 0; Integer i2 = i < v2.length ? Integer.parseInt(v2[i]) : 0; int compare = i1.compareTo(i2); if (compare != 0) return compare; } return 0; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/69284.html
摘要:注意因為方法輸入的是一個正則表達式所以不能直接用,而是要用,而的要轉(zhuǎn)義,所有要用代碼按照進行分割比對相應(yīng)的子串如果某個版本號更長,判斷其多余部分是否是,如果不是,則較長的較大,否則是一樣的。 Compare Version Numbers Compare two version numbers version1 and version2. If version1 > version2...
摘要:首先找整數(shù)部分的坐標(biāo)段,和都指向初值,令和一直向后遍歷到小數(shù)點為止。然后用將的整數(shù)段轉(zhuǎn)化為數(shù)值,進行比較若結(jié)果為大于或小于關(guān)系,直接返回結(jié)果若結(jié)果為相等,進行小數(shù)部分的比較。 Problem Compare two version numbers version1 and version2.If version1 > version2 return 1, if version1 < v...
Problem 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 an...
摘要:題目要求也就是說,比較版本號。思路一利用通過方法將版本通過分隔開,然后將每一段版本從轉(zhuǎn)化為進行比較思路二自己實現(xiàn)轉(zhuǎn)化為自己實現(xiàn)將轉(zhuǎn)化為,可以通過循環(huán)的方式。這是一個基本的算法。 題目要求 Compare two version numbers version1 and version2. If version1 > version2 return 1, if version1 < ve...
摘要:建立兩個堆,一個堆就是本身,也就是一個最小堆另一個要寫一個,使之成為一個最大堆。我們把遍歷過的數(shù)組元素對半分到兩個堆里,更大的數(shù)放在最小堆,較小的數(shù)放在最大堆。同時,確保最大堆的比最小堆大,才能從最大堆的頂端返回。 Problem Numbers keep coming, return the median of numbers at every time a new number a...
閱讀 1980·2021-11-24 10:45
閱讀 1468·2021-11-18 13:15
閱讀 4562·2021-09-22 15:47
閱讀 3941·2021-09-09 11:36
閱讀 2018·2019-08-30 15:44
閱讀 3097·2019-08-29 13:05
閱讀 2510·2019-08-29 12:54
閱讀 2003·2019-08-26 13:47