• [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 };
  • 相关阅读:
    Apache部署Django项目
    Docker
    常用算法
    Go之基本数据类型
    Go之流程控制
    Go基本使用
    Go安装与Goland破解永久版
    Linux
    详解java中的byte类型
    Linux统计文本中某个字符串出现的次数
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4640887.html
Copyright © 2020-2023  润新知