zoukankan      html  css  js  c++  java
  • [LeetCode] Longest Common Prefix

    Use the strs[0] as the reference string and then compare it with the remaining strings from left to right. Once we find a string with length less than strs[0] or different letters in the corresponding position, we cannot move on and should return the longest common prefix string lcp. Each time we finish checking a position and have not returned, we add the letter at that position to lcp.

     1 class Solution {
     2 public:
     3     string longestCommonPrefix(vector<string>& strs) {
     4         if (strs.empty()) return "";
     5         string lcp = "";
     6         int m = strs.size(), n = strs[0].length();
     7         for (int i = 0; i < n; i++) {
     8             for (int j = 1; j < m; j++)
     9                 if (strs[j].length() == i || strs[j][i] != strs[0][i])
    10                     return lcp;
    11             lcp += strs[0][i];
    12         }
    13         return lcp;
    14     }
    15 };
  • 相关阅读:
    linux安装jenkins
    linux安装python3.8
    python类继承多态
    python字典排序
    第一篇
    第十一周编程总结
    2019春第十周作业
    2019年寒假作业1
    2019年寒假作业3
    学期总结
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4640887.html
Copyright © 2011-2022 走看看