zoukankan      html  css  js  c++  java
  • 14. 最长公共前缀

    编写一个函数来查找字符串数组中的最长公共前缀。

    如果不存在公共前缀,返回空字符串 ""。

    示例 1:

    输入: ["flower","flow","flight"]
    输出: "fl"
    示例 2:

    输入: ["dog","racecar","car"]
    输出: ""
    解释: 输入不存在公共前缀。
    说明:

    所有输入只包含小写字母 a-z 。

    解:

    当字符串数组长度为 0 时则公共前缀为空,直接返回
    令最长公共前缀 ans 的值为第一个字符串,进行初始化
    遍历后面的字符串,依次将其与 ans 进行比较,两两找出公共前缀,最终结果即为最长公共前缀
    如果查找过程中出现了 ans 为空的情况,则公共前缀不存在直接返回
    时间复杂度:O(s)O(s),s 为所有字符串的长度之和

    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            string str_front;
    
            for(int i=0;i<strs.size();i++)
            {
                if(i==0)
                {
                    str_front=strs[i];
                    continue;            
                }
                int num=min(str_front.size(),strs[i].size());
                string front_tmp;
                for(int index=0;index<num;index++)
                {
                    //前面不相等,后面就不用比了
                    if(str_front[index]==strs[i][index])
                    {
                        front_tmp+=str_front[index];
                    }
                    else
                    {
                        break;
                    }
                }
                if(front_tmp.size()==0)
                {
                    return front_tmp;
                }
                else
                {
                    str_front=front_tmp;
                }
            }
            return str_front;
        }
    };
  • 相关阅读:
    219. Contains Duplicate II
    189. Rotate Array
    169. Majority Element
    122. Best Time to Buy and Sell Stock II
    121. Best Time to Buy and Sell Stock
    119. Pascal's Triangle II
    118. Pascal's Triangle
    88. Merge Sorted Array
    53. Maximum Subarray
    CodeForces 359D Pair of Numbers (暴力)
  • 原文地址:https://www.cnblogs.com/wangshaowei/p/12507359.html
Copyright © 2011-2022 走看看