LeetCode – 165. Compare Version Numbers

題目連結: https://leetcode.com/problems/compare-version-numbers/

練習提問:

Q: version1和version2是否有leading zeros? Ans: Ans
Q: version1和version2的長短是否ㄧ致? Ans: No
Q: version1和version2是否可能相等? Ans: Yes
Q: version1 > version2 回傳什麼值? Ans: 1
Q: version1 < version2 回傳什麼值? Ans: -1
Q: version1 == version2 回傳什麼值? Ans: 0

解法:

func compareVersion(_ version1: String, _ version2: String) -> Int {
    let version1Arr = version1.components(separatedBy: ".")
    let version2Arr = version2.components(separatedBy: ".")
    let count = version1Arr.count >= version2Arr.count ? version1Arr.count : version2Arr.count
    for i in 0 ..< count {
        let val1 = i < version1Arr.count ? (Int(version1Arr[i]) ?? 0) : 0
        let val2 = i < version2Arr.count ? (Int(version2Arr[i]) ?? 0) : 0
        if val1 > val2 {
            return 1
        } else if val1 < val2 {
            return -1
        }
    }
    return 0
}

print(compareVersion("1.01", "1.0001")) // leading zeros
print(compareVersion("1.1", "1.1.1"))   // length of two versions are not equal
print(compareVersion("1.2.1", "1.1.3")) // length of two versions are equal but version1's revision is larger than version2's revision