出处:http://blog.csdn.net/v_JULY_v
KEY1:左旋转字符串
题目:
把字符串前面的若干个字符移动到字符串的尾部,如把字符串abcdef左旋转2位得到字符串cdefab。
//左旋转字符串
#include<iostream>
#include<string>
using namespace std;
void rotate(char *start, char *end)
{
while(start != NULL && end != NULL && start < end)
{
char temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
void leftrotate(char *p, int m)
{
if(p == NULL)
return;
int len = strlen(p);
if(m > 0 && m <= len)
{
char *xstart, *xend;
char *ystart, *yend;
xstart = p;
xend = p + m -1;
ystart = p + m;
yend = p + len -1;
rotate(xstart, xend);
rotate(ystart, yend);
rotate(p, p + len -1);
}
}
int main()
{
char str[] = "abcdefghijk";
leftrotate(str, 3);
cout<<str<<endl;
}
KEY2:字符串包含问题
题目:
假设有两个由各种字母组成的字符串A和字符串B,其中字符串B中的字母数相对字符串A少。通过何种方法能最快的查出字符串B中的所有字母都包含在字符串A中呢?
如:字符串A:ABCDEFGHLMNOPQRS;字符串B:DCGSRQPO
答案是true。
//字符串包含问题
//时间复杂度O(m+n)
#include<iostream>
#include<string>
using namespace std;
int main()
{
string strOne = "ABCDEFGHIJKHER";
string strTwo = "DFGHJAAWE";
//辅助数组并清零
int hash[26] = {0};
//辅助数组中元素个数
int num = 0;
//扫描短字符串
for(int j = 0; j < strTwo.length(); j++)
{
int index = strTwo[j] - 'A';
if(hash[index] == 0)
{
hash[index] = 1;
num++;
}
}
//扫描长字符串
for(int i = 0; i < strOne.length(); i++)
{
int index = strOne[i] - 'A';
if(hash[index] == 1)
{
hash[index] = 0;
num--;
if(num == 0)
break;
}
}
if(num == 0)
cout<<"true"<<endl;
else
cout<<"false"<<endl;
}