Algorithm deliberate practice -LeetCode combat 14- longest common prefix (C ++)

Title: The longest common prefix

Link to the original question: the longest common prefix

Because if the prefix is ​​"public", so using an arbitrary string as a condition for the length of the cycle can be sequentially determined strs [0] of each character appears in every string. code show as below:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int num = strs.size();
        if(num == 0) return "";
        string s;
        for(int i = 0; i < strs[0].size(); i++){ //以strs[0]的长度为限
            int flag = 0;
            int j = 0;
            for(; j < num - 1; j++){
                if(strs[j][i] != strs[j + 1][i]) flag = 1;
            }
            if(flag == 1) break;
            else s.push_back(strs[j][i]);
        }
        return s;
    }
};

Here Insert Picture Description

Digression:
Only one person at the time wanted to get, will be afraid of losing. This feeling about the outcome, perhaps one of the many weaknesses of mankind. Sadly, the more anxious you want, the greater the possibility of losing.
- Gu "Sentimental Swordsman"

Published 16 original articles · won praise 0 · Views 270

Guess you like

Origin blog.csdn.net/DZZ18803835618/article/details/104854337