zoukankan      html  css  js  c++  java
  • 14. Longest Common Prefix 最长公共前缀子串

    14. Longest Common Prefix

    Write a function to find the longest common prefix string amongst an array of strings.

    可能题目说的很不清楚吧,233,踩的数量比赞的还多

    注意vector为空的时候提前返回ans就是了,空的vector访问时就会报错了。而这个水题后台是有空值得情况的。

    #include <bits/stdc++.h>
    using namespace std;
    
    class Solution {
    public:
       string longestCommonPrefix(vector<string>& strs) {
            //strs 字符串数组
            int n = strs.size();
            string ans;
            if(n == 0) return ans;
            string s = strs[0];
    
            for(int i = 0; i < s.length(); i++) { //以第一个字符串为基准,最长公共前缀不会超过第一个
                for(int p = 0; p < n; p++) { //遍历其他字符串
                    if(s[i] != strs[p][i] || strs[p].length() == i) {
                        return ans;
                    }
                }
                ans.push_back(strs[0][i]);
            }
            return ans;
        }
    
    };
    
    int main() {
        vector<string> ss;
        ss.push_back("leetcode");
        ss.push_back("leet");
        ss.push_back("lee");
        Solution sol;
        cout<<sol.longestCommonPrefix(ss)<<endl;
        return 0;
        }
  • 相关阅读:
    struts2.0利用注解上传和下载图片
    hibernate @ManyToOne
    Cookie会话管理
    ServletContext
    Servlet 1
    ArrayList
    BigInteger类和BigDecimal类
    Math类
    System类
    基本类型包装类
  • 原文地址:https://www.cnblogs.com/zhangmingzhao/p/7744977.html
Copyright © 2011-2022 走看看