首页 > 其他 > 详细

LeetCodeOJ. Longest Common Prefix

时间:2015-05-15 15:10:24      阅读:187      评论:0      收藏:0      [点我收藏+]

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

LeetCodeOJ. Longest Common Prefix

原文:http://www.cnblogs.com/hrhguanli/p/4505819.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!