Power button brushing questions: 14. The longest common prefix

Subject requirements

Insert picture description here
Insert picture description here

the whole idea

Select the first string in the string array as the benchmark, and compare it with the following strings in character order.

When the characters are not the same, record the index of the different characters and update it to the upper limit of the character comparison. Skip the current string and continue to compare the next string until all strings are compared.

Finally, a shortest upper limit is obtained, and the shortest upper limit is the length of the common substring.

Code

class Solution {
    
    
public:
    string longestCommonPrefix(vector<string>& strs) {
    
    
        if(strs.empty())
            return "";
        unsigned longestCommon = strs[0].size();
        //i代表字符串编号、j代表字符串中的字符编号
        for (size_t i = 1; i < strs.size(); i++)
        {
    
    
            for (size_t j = 0; j <= longestCommon; j++)
            {
    
    
            if (strs[0][j] != strs[i][j])
            {
    
    
                longestCommon = j;
                break;
            }
            }
        }
        return strs[0].substr(0, longestCommon);
    }
};

What learned

1. Pay attention to the case of an empty string for the string, and pay attention to the case of an empty container for the container. (I stepped on the pit once, and the vector was empty at the beginning without considering it)

Guess you like

Origin blog.csdn.net/youyadefeng1/article/details/113406573