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

    Longest Common Prefix 题解

    题目来源:https://leetcode.com/problems/longest-common-prefix/description/


    Description

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

    Solution

    
    class Solution {
    private:
        size_t getShortestStrIdx(vector<string>& strs) {
            size_t res = 0;
            auto minLen = strs[0].length();
            auto size = strs.size();
            decltype(minLen) tempLen;
            for (size_t i = 1; i < size; i++) {
                tempLen = strs[i].length();
                if (tempLen < minLen) {
                    minLen = tempLen;
                    res = i;
                }
            }
            return res;
        }
    public:
        string longestCommonPrefix(vector<string>& strs) {
            if (strs.empty())
                return "";
            string res = strs[getShortestStrIdx(strs)];
            auto size = strs.size();
            for (size_t i = 0; i < size; i++) {
                string::size_type len = 0;
                while (len < res.length() && len < strs[i].length()) {
                    if (res[len] == strs[i][len])
                        len++;
                    else
                        break;
                }
                if (len == 0)
                    return "";
                if (len < res.length())
                    res.resize(len);
            }
            return res;
        }
    };
    
    
    

    解题描述

    这道题题意是对给定的字符串数组,求所有字符串的最长公共前缀。我的算法是,先找到所有字符串中最短的一个,在用这个字符串作为结果初始值去跟其它所有字符串匹配。每次都从第0个字符开始,一旦第0个字符不匹配直接返回空串,反之则匹配到不匹配为止,每次刷新结果串的长度。

  • 相关阅读:
    2019ICPC徐州 H.Yuuki and a problem
    wprintf 输出中文
    bit数组
    Vs2010 Atl工程手工添加连接点
    dll非模态窗口不响应按钮消息
    VC中给控件添加ToolTip
    在Dialog中添加工具条
    在Dialog中添加状态栏
    Vc添加快捷键
    在VC中调用COM组件的方法
  • 原文地址:https://www.cnblogs.com/yanhewu/p/8383724.html
Copyright © 2011-2022 走看看