算法字符串全解
1.子序列:
题输入2个字符串,判断是否能从t中删除0个或者多个获得第二个,比如abcde删除变成bce 无法变为dc;
思路:
so easy 直接观察因为没有顺序的要求,直接看看先找到子序列第一个的字符在第一个字符串里面的位置,比如abcde bce里面的b第一次出现在父串里面的位置是b后面又c,c后面又有e正好符合,所以成立
利用一个指针指向第一个数组,宁一个指针指向第二个数组;
第一个数组只要出现第二个数组出现的数字,就把第二个数组后移
代码:
/*
1.输入2个字符串;
2.然后在第一个字符串里面找到第二个字符串第一个值,第二个j++;
加完后等于2的长度,输出“对”
*/
#include <iostream>
#include <string>
using namespace std;
int main()
{
string m,n;
cin>>m>>n;
int i,j=0;
for(i=0;i<m.size();++i)
{
if(m[i]==n[j])//如果第一个字符串里面出现第二个字符串的第二个字符串就往后移动
{
j++;
}
}
if(j==n.size()) cout<<"yes";
else cout<<"no";
}
2.谜题
利用字符串输入到二维数组,注意字符数组里面的每一行就是一行字符串,比如a[1][10]={1,2,3,4,5,6,7,8,9,10};
cout<<a[1];
{1,2,3,4,5,6,7,8,9,10};
思路:
1.用getline输入 这样就可以记住空格;
2.记住空格所在的x和y;
3.开始输入一个字符判断然后交换,注意注意注意,
交换后x和y要改变;
/*
5 4
TRGSJ
XPOKI
M VLN
WPABE
UQHCF
*/
#include <iostream>
#include <string>
using namespace std;
char a[10010][10010];
void swap(char &a,char &b)
{
char t=a;
a=b;
b=t;
}
int main()
{
string s;
char t;
int m,n,x,y;
cin>>m>>n;
for(int i=0;i<=m;++i)
{
getline(cin,s);
for(int j=0;j<s.size();++j)
{
a[i][j]=s[j];
if(a[i][j]==' ')
{
x=i;
y=j;
}
}
}
for(int i=0;i<n;++i)
{
cin>>t;
if(x<5&&y<5)
{
if (t == 'A')
{
swap(a[x][y],a[x-1][y]);
x--;
}
if (t == 'B')
{
swap(a[x][y],a[x+1][y]);
x++;
}
if (t == 'L')
{
swap(a[x][y],a[x][y-1]);
y--;
}
if (t == 'R')
{
swap(a[x][y],a[x][y+1]);
y++;
}
}
}
for(int i=0;i<m;++i)
{
cout<<a[i]<<endl;
}
return 0;
}
3.循环小数:
输入2个数字,输出a/b
输出循环小数,还有循环节长度
思路:
我们在纸上模拟过程,发现如果取余数的时候这个余数出现过了就break掉
代码:
/*
1.输入m,n;
2. a[0]存入m/n;
输出
3.接下来 输出'.'
4.每次将上一次的取余数*10在去除
5.
*/
#include <iostream>
using namespace std;
int a[10010];
int dp[10010];
int main()
{
int m,n,t,i=1;cin>>m>>n;
a[0]=m/n;
cout<<a[0]<<".";
m=(m%n)*10;
int ans=0;
while(1)
{
if(dp[m%n]>=1) break;
cout<<m/n;
dp[m%n]++;
ans++;
m=(m%n)*10;
i++;
}
cout<<endl;
cout<<ans;
//
}
4.DNA
直接看成一个二维数组就可以,观察答案每个序列出现的数字就是所有字符串对应位置上出现最多的字符
/*
1.输入m,n;
2.大的循环是m小的是n
大的先循环一遍,在里面循环一遍n
3.每次一列判断输出最大
5 8
TATGATAC
TAAGCTAC
AAAGATCC
TGAGATAC
TAAGATGT
*/
#include <iostream>
#include <string>
using namespace std;
char map[10010][10010];
int max(int t,int a,int c,int g)
{
if(t>=a&&t>=c&&t>=g) return 1;
else if(a>t&&a>c&&a>g) return 2;
else if(c>t&&c>a&&c>g) return 3;
else if(g>a&&g>t&&g>c) return 4;
}
int main()
{
int m,n;
cin>>m>>n;
for(int i=0;i<m;++i)
{
for(int j=0;j<n;++j)
{
cin>>map[i][j];
}
}
int t=0,a=0,c=0,g=0;
for(int i=0;i<n;++i)
{
t=0,a=0,c=0,g=0;
for(int j=0;j<m;++j)
{
if(map[j][i]=='T') t++;
else if(map[j][i]=='A') a++;
else if(map[j][i]=='C') c++;
else if(map[j][i]=='G') g++;
}
if(max(t,a,c,g)==1) cout<<'T';
else if(max(t,a,c,g)==2) cout<<'A';
else if(max(t,a,c,g)==3) cout<<'C';
else if(max(t,a,c,g)==4) cout<<'G';
}
}
好了字符串到此结束,接下来是递归了
希望大家多多做题,多多总结。