Longest Common Prefix

first iteration


class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        
        string prefix;
        
        // empty string vector
        if (strs.empty()) {
            return prefix;
        }
        
        int idx=0;
        char c;
        while (true) {
            
            // get character to be compared from first string
            if (idx < strs[0].size()) {
                c = strs[0][idx];
            } else {
                break;
            }
            
            // check if all strings has that character in the index
            //   - break out if either out of length or not same
            bool same = true;
            for (int i = 1; i < strs.size(); i++) {
                if (idx >= strs[i].size() || strs[i][idx] != c) {
                    same = false;
                    break;
                } 
            }
            
            // grow prefix if it is same otherwise, break out
            if (same) {
                prefix.push_back(c);
            } else {
                break;
            }
            
            idx++;
        }
        
        return prefix;
    }
};

2nd iteration with a little refactor


class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        
        string prefix;
        
        // empty string vector
        if (strs.empty()) {
            return prefix;
        }
        
        int len=0;
        while (true) {
            char var;
            int i = 0;
            for (; i < strs.size(); i++) {
                // get character to be compared from first string
                // could be '\0', but we break out as below
                if (i==0) {
                    var = strs[0][len];
                }
                
                // break out if run out of length or character comparision
                // failed
                if (len == strs[i].size() || strs[i][len] != var) {
                    break;
                } 
            }
            
            // this means compare with this character failed, break out 
            // and return whatever we got for prefix
            // NOTE: use the fact we early break out from for-loop or not to 
            // determine if we need continue the check
            if (i != strs.size()) {
                break;
            }
            
            // continue the checkfor longest common prefix
            prefix.push_back(var);
            len++;
        }
        
        return prefix;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值