1:数组全排列:
#include <stdio.h>
#include <iterator>
#include <iostream>
using namespace std;
void swap( int *p, int *q)
{
int temp;
temp = *p;
*p = *q;
*q = temp;
}
void perm(int list[], int k, int m)
{
if (k==m)
{
copy(list,list+m+1,ostream_iterator<int>(cout," "));
cout<<endl;
return;
}
for (int i=k; i<=m; i++)
{
swap(&list[k],&list[i]);
perm(list,k+1,m);
swap(&list[k],&list[i]);
}
}
int main(void)
{
int A[4] = {1,2,3,4};
perm(A, 0, 3);
system("pause");
}
python实现:
x = input()
x = x.split(',')
x = list(map(lambda n :int(n),x))
e = []
"""
for i in range(len(x)):
for j in range(len(x)):
for z in range(len(x)):
if i != j and j != z and i != z:
e=[x[i],x[j],x[z]]
print(e)
"""
def swap_(list_,a,b):
list_[a],list_[b] = list_[b],list_[a]
def perm(list_,k,m):
if k==m:
print(list_)
return
for i in range(k,m+1):
swap_(list_,k,i)
perm(list_,k+1,m)
swap_(list_,k,i)
perm(x,0,len(x)-1)
2,回文经典问题:
#include <iostream>
using namespace std;
int FindSubString(char *pch)
{
int count = 0;
char *p1 = pch;
while(*p1 != '\0')
{
if( *p1 == p1[1] - 1)
{
p1++;
count++;
}else
{
break;
}
}
int count2 = count;
while( *p1 != '\0')
{
if( *p1 == p1[1] + 1)
{
p1++;
count2--;
}else
{
break;
}
}
if(count2 == 0)
return count;
return 0;
}
void ModifyString( char *pText)
{
char *p1 = pText;
char *p2 = p1;
while(*p1 != '\0')
{
int count = FindSubString(p1);
if(count > 0)
{
*p2++ = *p1;
sprintf(p2,"%i",count);
while(*p2 != '\0')
{
p2++;
}
p1 += count + count +1;
}else {
*p2++ = *p1++;
}
}
}
void main(void)
{
char text[32] = "XYBCDCBABABA";
ModifyString(text);
printf(text);
system("pause");
}
3,
这道题题目例2有点问题:应该为:
s = "aaabcc"
dict = ["aaa","aab","bc"]
输出:
<br>aaabc</br>c
s0 = 'aaabcc'
dict = ['aaa','aab','bc']
'''寻找两字符串的交集'''
def overand(x,y):
if len(x) <= len(y):
for i in range(len(x)):
if x[i:len(x)] == y[0:len(x)-i]:
return x[i:len(x)+1]
elif len(x) > len(y):
for i in range(len(x)-len(y),len(x)):
if x[i:len(x)] == y[0:len(x)-i]:
return x[i:len(x)+1]
return ''
j = len(dict)-1
i = 0
'''对字典中所有元素遍历获取子串合并后的字典'''
while True:
if i == j:
break
s = overand(dict[i],dict[i+1])
if s != '':
i = i
dict[i] = dict[i][0:len(dict[i])-len(s)] + dict[i+1]
dict.pop(i+1)
j -= 1
else:
i += 1
for i in dict:
s0 = s0.replace(i,'<br>{}</br>'.format(i))
print(s0)