0 求字符串中连续出现次数最多的子串
#include<string>
#include<iostream>
using namespace std;
/* 求字符串中连续出现次数最多的字串
method:
for example:abcbcbcabc
子串有 a b c... / ab bc .../ abc.../ 等等
首先从第一个字符开始算起:以一个字符为子串单位逐个比较,然后以两个字符为子串单位逐个比较,三个字符的.... 长度一半的字符为单位
然后从第二字符开始算起(缩小字符串):重复上述步骤
从第三个。。。。
直到最后
*/
void SeqMaxSubStr(char* pStr, int length)
{
int index=-1;
int len=1;
int max_len=0;
int max_num=0;
int number=1;
int i,j;
for(i=0;i<length;i++){
len=1;
while(len<=(length-1)/2){
number=1;
for(j=i;j+len+len<=length;j+=len){
if(memcmp(pStr+j,pStr+j+len,len)==0)
number++;
else
break;
}
if(max_num<number){
max_num=number;
index=i;
max_len=len;
}
len++;
}
}
*(pStr+index+max_len)=0;
cout<<"max_num:"<<max_num<<endl;
cout<<"substr:"<<(pStr+index)<<endl;
}
int main(){
char s[100];
while(1){
cout<<"please input sstring:";
cin>>s;
SeqMaxSubStr(s,strlen(s));
}
return 0;
}
2. 求字符串中出现相同且长度最长的子字符串
#include<string>
#include<iostream>
using namespace std;
/* 求字符串中出现的相同且长度最长的字字符串
*/
void LengthMaxSubStr(char* pStr, int length)
{
int index=0;
int len=1;
int max_len=1;
int found=0;
int i,j;
for(i=0;i<length;i++){
len=(length-i)/2; //从长度最长的字串开始找起
while(len>=2){
found=0;
for(j=i+len;j+len<=length;j++){
if(memcmp(pStr+i,pStr+j,len)==0){
found=1;// found 跳出
break;
}
}
if(found){//跳出
break;
}
len--;
}
if(max_len<len){
max_len=len;
index=i;
}
}
*(pStr+index+max_len)=0;
cout<<"index:"<<index<<endl;
cout<<"max_len:"<<max_len<<endl;
cout<<"substr:"<<(pStr+index)<<endl;
}int main(){
char s[100];
while(1){
cout<<"please input sstring:";
cin>>s;
LengthMaxSubStr(s,strlen(s));
}
return 0;
}
优化:
void LengthMaxSubStr(char* pStr, int length)
{
int len=1;
int i,j;
len=(length)/2; //从长度最长的字串开始找起
while(len>=2){
for(i=0;i<length;i++){
for(j=i+len;j+len<=length;j++){
if(memcmp(pStr+i,pStr+j,len)==0){
goto A;
}
}
}
len--;
}
A:
*(pStr+i+len)=0;
cout<<"index:"<<i<<endl;
cout<<"max_len:"<<len<<endl;
cout<<"substr:"<<(pStr+i)<<endl;
}
3. 数字位的排序,即输入一个unsigned int型的整数,输出一个每位数字从小到大排列的unsigned int整数,例如输入"1325",输出"1235",输入:2009,输出:29。要求写出算法设计和程序代码。
template<typename T>
void insertion_sort(T *A, int size){
T temp;
int i,j;
for(i=1;i<size;i++){
j=i;
temp=A[i];
while(j && A[j-1]>temp){
A[j]=A[j-1];
j--;
}
A[j]=temp;
}
}
// 分别求出单个位上的数
// 进行插入排序
// 还原为整数
unsigned int sort_digit(unsigned int x)
{
unsigned int *p;
unsigned int a=x;
int num=0;
int i=0;
unsigned int sum=0;
while(a){// 求出位数
num++;
a/=10;
}
p=new unsigned int[num];
a=x;
while(a){
p[i]=a%10;
a/=10;
i++;
}
insertion_sort(p,num);
for(i=0;i<num;i++){
sum=sum*10+p[i];
}
delete p;
return sum;
}
int main(){
unsigned int x;
cin>>x;
cout<<sort_digit(x)<<endl;
return 0;
}// or, you can firstly translate the integer into char array and then sort them.