Identify Anagram

Problem:

=============

given two string with equal length, tell whether they are anagram.

 

 

Naive Solution : (Time complexity = O(n2) )

==============

1.  initiate two loops and match every letter of the first string with every letter of second string

2.  when you find one such matched character, flag them both as checked

3.  move on with your next computations, until At some point of time before the end of first string , you come across a mismatch (that you don't get a pair for one of the characters ) then return false straight away.

4.  return true

 

 

Solution 2 : (Time complexity = O(n) )

===============

1. Assuming your string to consist of only one cased of characters (say lower case or upper case) initialize an array say int counter[26] and initialize all values to 0 assume a variable "index_help" which is 65 (for upper cased) and 97(for lower cased). otherwise, initialize the int counter[52], to include both upper and lower cased.

2. Traverse through the string1 as:

for i in loop from 0 to string length of str1
count[ string1[i] - index_help ]++;


3. After this you'll have exact count of characters in string1.Now through string2 as

for i in loop from 0 to string length of str2
count[ string2[i] - index_help ]--;


4. Finally if they are anagrams the count array after the above loops should hold 0's throughout else can return false.

 

 

Code:

===============

bool isAnagram(string str1, string str2)

{

    int counter[52];

    int upper_index = 65;//lower cased is 97

    for (int i = 0; i < str1.length(); i++)

      counter[str1.at(i) - upper_index]++;

 

    for (int i = 0; i < str2.length(); i++)

      counter[str2.at(i) - upper_index]--;

 

    for (int i = 0; i < 52; i++)

      if(counter[i]) return false;

 

    return true;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值