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;
}
- Identify Anagram
- Identify
- IDENTIFY
- Identify
- anagram
- Anagram
- Anagram
- Anagram
- identify字段
- [Leetcode]Anagram
- poj-Anagram
- POJ1256 Anagram
- leetcode: anagram
- [LeetCode] Anagram
- poj1256 Anagram
- Valid Anagram
- Valid Anagram
- Valid Anagram
- POJ 1328 "Radar Installation"
- java学习之JNI 学习五 处理数组
- Zend Framework 1.10.1 开始使用 Zend_Session,Zend_Auth,和 Zend_Acl
- C++ 默认复制构造函数备忘
- swing弹出对话框
- Identify Anagram
- Cognos8 处理父子维度浅析
- 致新手:用VB6解决一些有趣的问题(七)
- CK3刷机步骤
- 彻底删除SQL Server2005的步骤
- 无法割舍
- CHM文章不能显示的问题
- 远程桌面问题,连接后马上断开,并显示“远程计算机已结束连接”或者不显示
- 婚礼上残疾的叔婶原来是公婆……