比较两个字符串是否为变位词

(1) 问题描述:如果两个字符串的字符一样,但是顺序不一样,被认为是兄弟字符串,问如何在迅速匹配兄弟字符串(如,bad和adb就是兄弟字符串)。
(2) 注意:第一点中讨论了字符串包含问题,但是不要以为两个字符串互相包含就是(变位词)兄弟字符串了,例如aabcde和edcba互相包含,但它们不是变位词。
(3) 解决方案:
思路一
给每个字母分配一个素数,可以通过判断两个字符串的素数乘积是否相等。跟上述素数法一样,时间复杂度也是O(n+m),需要跟大整数打交道。

#include<iostream> 
#include<string> 
#include<stdint.h> 
//#include<cstdint> // C++11 
using namespace std; 

bool Compare(string s1, string s2) 
{ 
  unsigned int primeNum[26] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47, 
            53,59,61,67,71,73,79,83,89,97,101}; 
  uint64_t ch = 1; 

  for(int i=0; i<s1.size(); ++i) 
  { 
    ch = ch*primeNum[s1[i]-'a']; 
  } 

  for(int i=0; i<s2.size(); ++i) 
  { 
    ch = ch/primeNum[s2[i]-'a']; 
  } 

  if(ch == 1) 
    return true; 
  else
    return false; 
} 

int main() 
{ 
  string s1 = "abandon"; 
  string s2 = "banadon"; 
  if(Compare(s1, s2)) 
    cout << "They are brother words!" << endl; 
  else
    cout << "They aren't brother words!" << endl; 
  return 0; 
} 

> 思路二

将两个字符串按照字母表顺序排序,看排序后的字符串是否相等,如果相等则是兄弟字符串(变位词)。这种方法的时间效率根据你使用的排序算法不同而不同。当然,你可以自己写排序算法,这里我们使用C++的STL中的sort()函数对字符串进行排序。

#include<iostream> 
#include<algorithm> 
#include<string> 
using namespace std; 

// 自定义序函数(二元谓词) 
bool myfunction(char i, char j) 
{ 
  return i > j; 
} 

bool Compare(string s1, string s2) 
{ 
  // 采用泛型算法对s1,s2排序,sort()采用的是快速排序算法 
  sort(s1.begin(), s1.end(), myfunction); 
  sort(s2.begin(), s2.end(), myfunction); 
  if(!s1.compare(s2)) // 相等返回0 
    return true; 
  else
    return false; 
} 

int main() 
{ 
  string s1 = "abandon"; 
  string s2 = "banadon"; 
  if(Compare(s1, s2)) 
    cout << "They are brother words!" << endl; 
  else
    cout << "They aren't brother words!" << endl; 
  return 0; 
} 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值