LeetCode 14. 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.

代码 C++

  • 思路一、
    1,找到一共多少行
    2,找到行字符串里面的最短长度 (因为公共字符串 <= 最短长度)
    3,写一个子函数 fab 逐一比较每行的第 j 位是否相同
    4,sunstr 返回公共字符串
class Solution {
public:
    string longestCommonPrefix(vector& strs) {
        int rows = strs.size();
        
        // 如果输入为 [] , 则返回 ""
        if(rows == 0){
            return "";
        }
        
        int cols = strs[0].size();
        
        // 找到最短的行
        for(int i=1; i < rows; i++){
            if(cols > strs[i].size()){
                cols = strs[i].size();
            }
        }
        
        // 如果里面有 "", 则最长前缀为 ""
        if(cols == 0){
            return "";
        }
        
        int j = 0;
        while(j < cols){
            if(fab(strs, rows, j)){
                j = j + 1;
            }
            else{
                break;
            }
        }
        
        if(j == 0){
            return "";
        }
        else{
            return strs[0].substr(0, j);
        }
        
    }
    
    // 判断第 j 位是否相同
    bool fab(vector& strs, int rows, int j){
        char tt;
        for(int i=0; i < rows; i++){
            if(i == 0){
                tt = strs[0][j];
            }
            else{
                if(tt != strs[i][j]){
                    return  false;
                }
            } 
        }
        return true;
    }
};

总结展望

你可能感兴趣的:(LeetCode 14. Longest Common Prefix)