• leetcode 14. Longest Common Prefix


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

    If there is no common prefix, return an empty string "".

    Example 1:

    Input: ["flower","flow","flight"]
    Output: "fl"
    

    Example 2:

    Input: ["dog","racecar","car"]
    Output: ""
    Explanation: There is no common prefix among the input strings.
    

    Note:

    All given inputs are in lowercase letters a-z.

    思路:直接判断每一个位置是否字符相同,直到不同。

     1 class Solution {
     2 public:
     3     string longestCommonPrefix(vector<string>& strs) {
     4         int len = strs.size();
     5         if (len == 0)
     6             return "";
     7         for (int i = 0; i < strs[0].length(); ++i) {
     8             char c = strs[0][i];
     9             for (int j = 1; j < strs.size(); ++j) {
    10                 if (i < strs[j].length() && strs[j][i] == c) {
    11                     continue;
    12                 } else {
    13                     return strs[0].substr(0, i);
    14                 }
    15             }
    16         }
    17         return strs[0];
    18     }
    19 };
  • 相关阅读:
    Matlab 画图
    OfferCome-0531
    OfferCome--0528
    剑指offer(2)
    剑指offer(1)
    MySQL的自增主键
    java Junit 测试
    sql 注入问题
    Facebook Libra
    markdown的博客
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11554989.html
Copyright © 2020-2023  润新知