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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章