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

[LeetCode] Longest Common Prefix

时间:2014-10-25 00:52:44      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   on   

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

题目言简意赅,貌似也不难,暴力法用一个char *数组存放strs里每个元素的起始地址,然后循环,同时把所有指针向前移动,

如果有其中有一个字符失配就算完成,写的时候出现一个bug就是在移动指针的时候没有判断是否超出了那个string的长度,导致莫名其妙的问题。

string longestCommonPrefix(vector<string> &strs) {
    if (strs.size() == 0) return string();
    if (strs.size() == 1) return strs[0];
    char *ptrs[strs.size()];
    for (int i = 0; i < strs.size(); i++) {
        ptrs[i] = &(strs[i][0]);
    }
    
    bool failed = false;
    int bias = 0;
    int i;
    string res;
    while (!failed){
        for (i = 1; i < strs.size(); i++) {
            if ((bias >= strs[i].size() || bias >= strs[i-1].size()) || *(ptrs[i]+bias) != *(ptrs[i-1]+bias)){
                failed = true;
                break;
            }
        }
        if (!failed){
            res += strs[0][bias];
            bias++;
        }
    }
    
    return res;
}

 

[LeetCode] Longest Common Prefix

标签:style   blog   color   io   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/agentgamer/p/4049596.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!