zoukankan      html  css  js  c++  java
  • leetcode 14. longest common prefix

    this is a easy question

    the intuition of our method: we should record the max prefix from the first string to the last one.

    class Solution {
    public:
    string longestCommonPrefix(vector<string>& strs) {
    if(strs.empty())
    return "";
     
    string pre(strs[0]);
    // cout<<strs[0]<<endl;
    int n=strs.size();
    cout<<n<<endl;
    int maxl=strs[0].length();
    if(n==1)
    return pre;
    int m;
     
    for(int i=1;i<n;i++)
    {
    m=strs[i].length();
    maxl=min(maxl, m);
    for( int j=maxl-1;j>=0;j--)
    {
    if(pre[j]!=strs[i][j])
    {
    maxl=j;
    }
    }
     
    }
     
     
    return pre.substr(0,maxl);
    }
     
     
    };
    • we should care about the empty vector.

    • using the first string as the longest prefix p _and the length(p) , then exhaustively search every string _s | if s.length()<p.length() (first step) | for i=0-length(p) | | :--- | :--- | | length(p)=s.length() | if(s[i]!=p[i]) break; i is longest prefix |

    For improve the speed, we can get the shortest length of those strings firstly. because the longest prefix must be shorter than the shortest string.

    exit: Ctrl + ↩
    class Solution {
    public:
    string longestCommonPrefix(vector<string>& strs) {
    if ( strs.empty() ) return std::string();
     
    unsigned minSize = strs[0].size();
    unsigned strsSize = strs.size();
    for (unsigned i=1; i<strsSize; ++i) {
    minSize = std::min(minSize, (unsigned)strs[i].size());
    }
     
    char c;
    unsigned j, k;
    for (j=0; j<minSize; ++j) {
    c = strs[0][j];
    for (k=1; k<strsSize; ++k) {
    if ( strs[k][j]!=c ) break;
    }
    if ( k<strsSize && strs[k][j]!=c ) break;
    }
     
    return std::string(strs[0],0,j);
    }
    };
  • 相关阅读:
    服务器做系统备份时失败
    PHPMailer中文乱码问题的解决方法
    html字符串分行显示
    Oracle中取某几个数的最大值最小值
    分布式事务之 Seata
    org.apache.dubbo 2.7.7 服务端处理请求及时间轮(失败重试)
    org.apache.dubbo 2.7.7 服务消费源码
    org.apache.dubbo 2.7.7 服务发布注册源码
    org.apache.dubbo 2.7.x 再聚首
    spring-cloud-gateway 服务网关
  • 原文地址:https://www.cnblogs.com/fanhaha/p/7206733.html
Copyright © 2011-2022 走看看