LeetCodeOJ. Longest Common Prefix

试题请参见: https://oj.leetcode.com/problems/longest-common-prefix/

题目概述

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

解题思路

这也是比较简单的算法提, 只需比较比较数组中每个字符串的第i位即可, 直至不匹配为止.
记录此时i的值, 则为最长公共前缀.

源代码

class Solution {
public:
    std::string longestCommonPrefix(std::vector<std::string> &strs) {
        bool isMatched = true;
        int index = 0;
        char character = 0;

        if ( strs.size() == 0 ) {
            return "";
        }

        do {
            character = strs[0][index];

            for ( size_t i = 0; i < strs.size(); ++ i ) {
                if ( index >= strs.at(i).size() || strs.at(i).at(index) != character ) {
                    isMatched = false;
                }
            }
            
            ++ index;

        } while ( isMatched );

        return strs[0].substr(0, index - 1);
    }
};

发布了50 篇原创文章 · 获赞 1 · 访问量 9万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章