【LeetCode】求字符串数组的最大公共前缀:Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

1. 纵向扫描,代码如下:

class Solution {
public:
    string longestCommonPrefix(vector& strs) {
        if(strs.size() == 0) return "";
        
        int maxInd = 0;
        for(int i = 0; i < strs[0].size(); i++) {
            for(int j = 1; j < strs.size(); j++) {
                if(strs[j][i] != strs[0][i]) {
                    return strs[0].substr(0, i);
                } 
            }
        }
        
        return strs[0];
    }
};

2. 横向扫描,代码如下:

class Solution {
public:
    string longestCommonPrefix(vector& strs) {
        if(strs.empty()) return "";
        
        int maxCommonLen = strs[0].size();
        
        for(int i = 1; i < strs.size(); i++) {
            for(int j = 0; j < maxCommonLen; j++) {
                if(strs[i][j] != strs[0][j]) {
                    maxCommonLen = j;
                    break;
                }
            }
        }
        
        return strs[0].substr(0, maxCommonLen);
    }
};

 

你可能感兴趣的:(数据结构与算法)