美文网首页
LeetCode 14. Longest Common Pref

LeetCode 14. Longest Common Pref

作者: cb_guo | 来源:发表于2019-04-06 12:09 被阅读0次

    题目描述

    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<string>& 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<string>& 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 Pref

          本文链接:https://www.haomeiwen.com/subject/kvkriqtx.html