Chinaunix首页 | 论坛 | 博客

分类: C/C++

2010-09-30 21:16:32

  同学说他去趋势科技笔试时有道编程题目,自己写了个解法:


/*
 *在一个字符串中一个特定子串包含字符的个数,该字符串的每个字符都不相同!
 *(C) LC
 */


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

#define    MaxLen    30

int is_same(char *, int, int);

int main(void)
{
    int    max = 1;//保存最长目标字串的字符个数
   
int    leng, count = 1;//字符串的具体长度
   
int    i = 0;
    int    j = 1;
    char   str[MaxLen];
    
    printf("-------------------------------------\n");
    printf("|please input the string, thank you!|\n");
    printf("-------------------------------------\n");
    
    fgets(str, MaxLen, stdin);

    while(str[i] != '\0')    
    {
        while(!is_same(str, i, j) && str[j] != '\0')
        {
            count++;
            j++;
        }
        if(count > max)
            max = count - 1;
        if(str[j] == '\0')
            break;
        else
        {
            count = 1;
            i = is_same(str, i ,j);
            j = i + 1;
        }
    }
    printf("max = %d\n", max);

    return    0;
}

int is_same(char *str, int begin, int current)
{
    int    flag = 0;//当前字符和以前的
    int    i;
    for(i = begin; i < current; i++)
        if(str[i] != str[current])
            ;
        else
        {
            flag = i + 1;
            return    flag;
        }
    return    flag;        
}


阅读(2321) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~