LeetCode

165. Compare Version Numbers

2017-01-24  本文已影响9人  小万叔叔
/*
 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
 */

/*
 切割字符串,如果长度为1,补足为2
 Error:可能会出现多个版本,因此需要根据两个版本中的居多者补齐,然后
 输入一个比较函数,比较每一个子版本
 */

func compareVersion(_ version1: String, _ version2: String) -> Int {
    
    var v1Array = version1.components(separatedBy: ".")
    var v2Array = version2.components(separatedBy: ".")
    
    let versionLength = max(v1Array.count, v2Array.count)
    
    for _ in 0..<versionLength-v1Array.count {
        v1Array.append("0")
    }
    
    for _ in 0..<versionLength-v2Array.count {
        v2Array.append("0")
    }
    
    //如果相等,则继续比较,如果不等,则直接返回结果
    func compareResult(_ v1: String, _ v2: String) -> Int {
        if Int(v1)! > Int(v2)! {
            return 1
        }
        else if Int(v1)! < Int(v2)! {
            return -1
        }
        else {
            return 0
        }
    }
    
    var result = 0
    for i in 0..<versionLength {
        let ret = compareResult(v1Array[i], v2Array[i])
        if ret != 0 {
            result = ret
            break
        }
    }
    
    return result
}

compareVersion("1.0.1", "1")

上一篇 下一篇

猜你喜欢

热点阅读