zoukankan      html  css  js  c++  java
  • 找出两个字符串中最大子字符串,如"abractyeyt","dgdsaeactyey"的最大子串为"actyet

    // 最大子字符串.cpp : 定义控制台应用程序的入口点。
    //
    //找出两个字符串中最大子字符串,如"abractyeyt","dgdsaeactyey"的最大子串为"actyet"
    
    #include <iostream>
    #include <string>
    using namespace std;
    
    string MaxSameStr(string str1,string str2)
    {
    	string result;
    	int max=0,first;
    	int len=0;//相同字符串的长度
    	int k,q;
    	
    	//穷举
    	for(unsigned int i=0;i<str1.length();i++)
    		for(unsigned int j=0;j<str2.length();j++)
    		{
    			unsigned int k=i;
    			unsigned int q=j;
    			if (str1[k]==str2[q])//发现相同的字母
    			{
    				first=k;  //标记起始位置
    				while(str1[k]==str2[q]&&q<str2.length()&&k<str1.length())//继续比较后面的是否也相同
    				{
    					k++;q++;
    				}
    				len=k-first;
    				if(len>max)//是否为目前最长字符串
    				{
    					max=len;
    					string temp(str1,first,len);
    					result=temp;
    				}
    			}
    		}
    		return result;
    }
    int main()
    {
    	string Str1,Str2;
    	cout<<"请输入两个字符串"<<endl;
    	cin>>Str1>>Str2;
    	cout<<"结果为"<<MaxSameStr(Str1,Str2)<<endl;
    	return 0;
    }
    //特别是这句while(str1[k]==str2[q]&&q<str2.length()&&k<str1.length())要加上后面的q<str2.length()&&k<str1.length(),不然会导致字符串越界。。
  • 相关阅读:
    RedHat/CentOS根目录扩容
    VNC安装配置
    网络命名空间
    Linux 端口信息查看
    Linux实际常用命令
    yum的配置文件介绍
    Linux下查/删/替 命令(转)
    CentOS/redhat使用光盘镜像源
    数据库的附加和分离
    Corrupted Metadata/failed to mount /sysroot
  • 原文地址:https://www.cnblogs.com/zhangdongsheng/p/1952917.html
Copyright © 2011-2022 走看看