判断两个字符串是否匹配

原文地址:http://blog.youkuaiyun.com/v_JULY_v/article/details/6347454。同时也向大家推荐这个文章的博主,技术大牛。

如果两个字符串中所含字符的个数和对应的字符都相等,我们说这两个字符串匹配,比如:abcdea,aabcde。则这两个字符串相等。

特别喜欢这个方法,故转到我空间来,以便记录。

#include <iostream>  
#include <string>  
using namespace std;  
  
bool Is_Match(const char *strOne,const char *strTwo)  
{  
    int lenOfOne = strlen(strOne);  
    int lenOfTwo = strlen(strTwo);  
  
    // 如果长度不相等则返回false  
    if (lenOfOne != lenOfTwo)  
        return false;  
  
    // 开辟一个辅助数组并清零  
    int hash[26] = {0};  
      
    // 扫描字符串  
    for (int i = 0; i < strlen(strOne); i++)  
    {  
        // 将字符转换成对应辅助数组中的索引  
        int index = strOne[i] - 'A';  
          
        // 辅助数组中该索引对应元素加1,表示该字符的个数  
        hash[index]++;  
    }  
  
    // 扫描字符串  
    for (int j = 0; j < strlen(strTwo); j++)  
    {  
        int index = strTwo[j] - 'A';  
          
        // 如果辅助数组中该索引对应元素不为0则减1,否则返回false  
        if (hash[index] != 0)  
            hash[index]--;  
        else  
            return false;  
    }  
    return true;  
}  
  
int main()  
{  
    string strOne = "ABBA";  
    string strTwo = "BBAA";  
      
    bool flag = Is_Match(strOne.c_str(), strTwo.c_str());  
      
    // 如果为true则匹配,否则不匹配  
    if (flag == true)  
        cout << "Match" << endl;  
    else  
        cout << "No Match" << endl;  
    return 0;  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值