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);
    }
    };
  • 相关阅读:
    oracle查询锁表解锁语句
    转:js,jQuery 排序的实现,网页标签排序的实现,标签排序
    禁止页面缩放功能
    js 操作 cookie
    random模块
    以及模块的四种形式模块的四种形式和模块的调用
    函数的调用
    函数的返回值
    可变长参数
    函数的重点内容
  • 原文地址:https://www.cnblogs.com/fanhaha/p/7206733.html
Copyright © 2011-2022 走看看