Identify Anagram

来源:互联网 发布:python 创建两个字典 编辑:程序博客网 时间:2024/06/04 17:42

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;

}

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 手机网速慢怎么办vivox9 vivox9手机反应慢怎么办 手机dns延迟高怎么办 管家dns延迟高怎么办 wi-fi信号差怎么办 无线dns未响应怎么办 影客票务过期怎么办 默认主页改不了怎么办 快递派件不成功怎么办 韵达快递不派件怎么办 中通快递不派件怎么办 理财回执单丢失怎么办 理财回单丢了怎么办 杭州市老年优待卡怎么办 网络连接不到服务器怎么办 即时库存有负数怎么办 电脑软件被拦截怎么办 超市无条码商品怎么办 场外期权有诈骗怎么办 ip地址访问受限怎么办 电脑ip地址受限怎么办 百度云资源打不开怎么办 百度网盘看文件字太小怎么办 密码输入三次错误怎么办 notes邮箱满了怎么办 小米8买不到怎么办 小米付款不发货怎么办 小米金融还款中怎么办 股票遇到闪崩怎么办 微信插件没有怎么办 excel打印太小怎么办 工地临时人员死亡怎么办 哺乳期乳腺增生疼怎么办 哺乳期有乳腺增生怎么办 哺乳期得了乳腺增生怎么办 中等教育认证花名册丢失怎么办 哺乳期囊性结节怎么办 乳腺增生堵奶怎么办 月子期乳房增生怎么办 母乳期乳腺增生怎么办 上市公司破产了股票怎么办