求一个字符串中连续出现次数最多的子串

本文介绍了一个使用C语言实现的算法,用于找出给定字符串中连续出现次数最多的子串及其出现次数。示例代码针对字符串abcbcbcabc进行了测试,结果显示连续出现次数最多的子串为bc,共出现了3次。

http://blog.youkuaiyun.com/huangkangying/article/details/6443302

求一个字符串中连续出现次数最多的子串,例如:abcbcbcabc, 这个串中连续出出次数最多的子串是bc, 它出现了3次。

以下是我的实现代码,用c语言实现,已经编译通过。


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

int	count= 0;
char	sub_str[256];

void	find_str( char *str )
{
	int	str_len = strlen( str );
	int	i, j, k;
	int	temp_cnt = 0;

	for( i = 0; i < str_len; i++ )
	{
		for( j = i + 1; j < str_len; j++ )
		{	
			int	n = j - i;
			temp_cnt = 1;
			if( strncmp( &str[i], &str[j], n ) == 0 )
			{
				temp_cnt++;
				for( k = j +n; k < str_len; k+= n )
				{
					if( strncmp( &str[i], &str[k], n ) == 0 )
						temp_cnt++;
					else
						break;							
				}
				if( temp_cnt > count )
				{
					count = temp_cnt;
					strncpy( sub_str, &str[i], n );
					//memcpy( sub_str, &str[i], n );  // 也比较关键
				}

			}
		}
	}
}

int main( void )
{
	char	*str = "abcbcbcabc";
	find_str( str );
	printf( "%d, %s\n", count, sub_str);
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值