找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 258|回复: 1

第一个最长子串

[复制链接]

205

主题

173

回帖

6925

积分

论坛元老

积分
6925
发表于 2013-6-15 23:31:41 | 显示全部楼层 |阅读模式


在04月27日题目的基础上,找出chars字符串在source中的第一个最长子串(当找到第一个字母相同时再往后找有没有更多匹配的,如果没有,就返回一个字母了)
例:source表示字符串"ABCDEFGH" chars表示字符串"YURABJEFGH",输出结果为字符串为"AB",如果chars表示字符串为"YURAJEFGH",返回"A"

205

主题

173

回帖

6925

积分

论坛元老

积分
6925
 楼主| 发表于 2013-6-15 23:32:12 | 显示全部楼层
参考答案:

#include <stdio.h>
#include <malloc.h>
#define MAX_LENGHT 256

/*Get the longest chars between source and cp*/
size_t find_longest_length(const char *source, const char *cp)
{
        size_t len = 0;
        while( *(++source) == *(++cp) )
                len++;
        return len;
}
/*similar to strcpy*/
char *mystrcpy(char *pfind, const char *cp)
{
        int longest = 0;
        char *ptmp = pfind;
        while( *ptmp++ = *cp++ )
        {
                longest++;
                /*2 is for space to store the first character and &#39;\0&#39;*/
                if(longest == MAX_LENGHT -2 )
                        break;
        }
        return pfind;
}

char *find_char(const char *source, const char *chars)
{
        char *cp;
        char *pfind;

        pfind = (char *)malloc(MAX_LENGHT);
        if( NULL == pfind )
        {
                fprintf(stderr,"out of memory!\n");
                return NULL;
        }

        if( source != NULL && chars != NULL )
        {
                for( ; *source != &#39;\0&#39;; source++ )
                {
                        for( cp = chars; *cp!= &#39;\0&#39;; cp++ )
                        {
                                if( *source == *cp )
                                {
                                        mystrcpy(pfind, cp);/*copy string from cp to pfind*/
                                        *(pfind + find_longest_length(source,cp) +1) = &#39;\0&#39;;
                                        return pfind;
                                }
                        }
                }
        }
        /*Not found char in source*/
        if(pfind)
                free(pfind);
        pfind = NULL;

        return NULL;
}
int main(int argc,char *argv[])
{
        char *cp;

        cp = find_char(argv[1],argv[2]);

        if(cp == NULL)
        {
                printf("Not found chars in source!\n");
                return 0;
        }
        else
        {
                printf("The longest string is:[%s]\n",cp);
                free(cp);
                cp = NULL;

        }
        return 0;
}
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

果子博客
扫码关注微信公众号

Archiver|手机版|小黑屋|风叶林

GMT+8, 2026-2-1 14:01 , Processed in 0.077476 second(s), 20 queries .

Powered by 风叶林

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表