zoukankan      html  css  js  c++  java
  • 14. Longest Common Prefix

    题目:
    LeetCode:14. Longest Common Prefix

    描述:

    Write a function to find the longest common prefix string amongst an array of strings.
    求字符串数组的最长公共前缀。
    

    分析:

     思路:
     1、遍历vector中每个字串,将之与之前得到的公共字串进行比较;
     2、将首个字符串作为初始的公共字串比较;
     3、由于是最长的前缀字串,将vector中字符串和公共字串依次比较,当匹配到不相同字符,返回并得到新的公共字串。
    

    代码:

    /*
     ** @brief:
     ** @param[in]: strs,The string to be processed
     ** return: the common string
     */
    string longestCommonPrefix(vector<string>& strs) {
        if ( 0 == strs.size())
        {
            return "";
        }
        else if (1 == strs.size())
        {
            return strs[0];
        }
        else
        {
            string strPrefix = strs[0];
            for (int i = 1; i < strs.size(); ++i)
            {
                int j = 0;
                while (strPrefix[j] == strs[i][j] && j < strPrefix.length())
                {
                    ++j;
                }
                strPrefix = strPrefix.substr(0, j);
            }
            return strPrefix;
        }
    }
    

    备注:
    本题在实现循环匹配的逻辑处可以进行算法的优化,提升性能。

  • 相关阅读:
    Catalan数
    C# & LINQ 对象克隆
    Rotate Image
    反转链表
    QtCreator调试程序时GDB崩溃
    Regular Expression Matching
    Wildcard Matching
    DFA与NFA
    Set Matrix Zeroes
    PCA原理
  • 原文地址:https://www.cnblogs.com/liuwfuang96/p/7086630.html
Copyright © 2011-2022 走看看