码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCodeOJ. Longest Common Prefix

时间:2015-05-15 15:13:04      阅读:104      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!