【IT面试题】字符串

出处: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;
}


   


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值