试题请參见: 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); } };