首页 > 其他 > 详细

[Leetcode]-Longest Common Prefix

时间:2015-06-25 14:05:20      阅读:245      评论:0      收藏:0      [点我收藏+]

// 1、判断strs的长度,如果为0则返回空字符
// 2、找出strs中最短的字串
// 3、采用循环查询的方式依次匹配是否和最短字串相符
// 4、循环中实时更新查询的长度index

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char* longestCommonPrefix(char** strs, int strsSize) 
{
    if(strsSize < 1)
        return "";
    int index = strlen(strs[0]) ;
    int i = 0, j =0, m=0;
    for(i=0;i<strsSize-1;i++) //求取最短字串的长度
    {
        if(strlen(strs[i+1])<strlen(strs[i]))
        {
            index = strlen(strs[i+1]);
            m = i+1;
        }
    }
    printf("the most short size of string is :%d \n ",index);
    char *r = (char*)malloc(sizeof(char) * index);
    strcpy(r,strs[m]);
    printf("r is :%s \n ",r);
    int tem = 0;
    for(i=0;i<strsSize;i++)
    {
        tem = 0;
        for(j=0;j<index;j++)
        {
            if(r[j] == strs[i][j])
            {
                tem++;
            }
            else
            {
                r[j] = ‘\0‘;
                break;
            }   
        }
        if(tem == 0)  return ("");
        if(tem < index) index = tem;
    }

    return r;
}


int main(char argc,char** argv)
{
    char a3[][30] = {{"xiabodan_firstpoint!"},{"xiabodan_second!"},{"xiabodan_thirdpoint!"}};
    char *a0 = "xiabodan_first!";
    char *a1 = "xiabodan_secondpoint!";
    char *a2 = "xiabodan_thirdpoint!";

    char *p3[3] ;
    int i = 0;
    for(i=0;i<3;i++)
    {
        p3[i] = a3[i];
    }
    //p3[0] = a0;
    //p3[1] = a1;
    //p3[2] = a2;
    //printf("strlen  str is: %d \n",strlen(p3)); 
    char* lpc = longestCommonPrefix(p3,3);
    printf("longestCommonPrefix str is: %s \n",lpc);  //输出应该是xiabodan_才对
}

[Leetcode]-Longest Common Prefix

原文:http://blog.csdn.net/xiabodan/article/details/46635065

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