LeetCode 165 Compare Version Numbers

字符串版本号比较思路与复杂度
博客介绍了字符串版本号比较的思路,即根据“.”分割字符串得到每段数字并依次比较,还提到要考虑输入版本的合法性。同时给出了该方法的时间复杂度为O(n),空间复杂度为O(1)。

思路

字符串根据"."得到每段的数字,依次进行比较即可。
follow up:
考虑尽可能多的corner case,判断输入的version是否合法。

复杂度

时间复杂度O(n), 空间复杂度O(1)

代码

class Solution {
    public int compareVersion(String version1, String version2) {
        // Compare each character in 2 strings.
        // The larger string wins
        // Longer string wins: one of the 2 strings hits the end, and they are the same so far. 
        
        int index1 = 0, index2 = 0;
        while(index1 < version1.length() || index2 < version2.length()) {
            int v1 = 0, v2 = 0;
            while(index1 < version1.length() && version1.charAt(index1) != '.') {
                v1 *= 10;
                v1 += version1.charAt(index1) - '0';
                index1++;
            }
            
            while(index2 < version2.length() && version2.charAt(index2) != '.') {
                v2 *= 10;
                v2 += version2.charAt(index2) - '0';
                index2++;
            }
            
            if(v1 < v2) return -1;
            if(v1 > v2) return 1;
            // or infinite loop occurs
            index1++;
            index2++;
        }
        return 0;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值