两个字符串是否是由相同字母(出现次数也相同)组成的
2016-12-15 19:15
246 查看
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
Algorithm
An anagram is produced by rearranging the letters of ss into tt.
Therefore, if tt is
an anagram of ss,
sorting both strings will result in two identical strings. Furthermore, if ss and tt have
different lengths, tt must
not be an anagram of ss and
we can return early.
Complexity analysis
Time complexity : O(n
\log n)O(nlogn).
Assume that nn is
the length of ss,
sorting costs O(n
\log n)O(nlogn) and
comparing two strings costs O(n)O(n).
Sorting time dominates and the overall time complexity is O(n
\log n)O(nlogn).
Space complexity : O(1)O(1).
Space depends on the sorting implementation which, usually, costs O(1)O(1) auxiliary
space if
a copy of the string so it costs O(n)O(n) extra
space, but we ignore this for complexity analysis because:
It is a language dependent detail.
It depends on how the function is designed. For example, the function parameter types can be changed to
Algorithm
To examine if tt is
a rearrangement of ss,
we can count occurrences of each letter in the two strings and compare them. Since both ss and tt contain
only letters from a-za−z,
a simple counter table of size 26 is suffice.
Do we need two counter tables for comparison? Actually no, because we could increment the counter for each letter in ss and
decrement the counter for each letter intt,
then check if the counter reaches back to zero.
counter[t.charAt(i) - 'a']--;
}
for (int count : counter) {
if (count != 0) {
return false;
}
}
return true;
}[/code]
Or we could first increment the counter for ss,
then decrement the counter for tt.
If at any point the counter drops below zero, we know that tt contains
an extra letter not in ss and
return false immediately
Complexity analysis
Time complexity : O(n)O(n).
Time complexity is O(n)O(n) because
accessing the counter table is a constant time operation.
Space complexity : O(1)O(1).
Although we do use extra space, the space complexity is O(1)O(1) because
the table's size stays constant no matter how large nn is.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
Approach #1 (Sorting) [Accepted]
AlgorithmAn anagram is produced by rearranging the letters of ss into tt.
Therefore, if tt is
an anagram of ss,
sorting both strings will result in two identical strings. Furthermore, if ss and tt have
different lengths, tt must
not be an anagram of ss and
we can return early.
public boolean isAnagram(String s, String t) { if (s.length() != t.length()) { 4000 //若长度不同则直接返回否 return false; } char[] str1 = s.toCharArray(); //String.toCharArray() 方法将字符串转换为字符数组 char[] str2 = t.toCharArray(); Arrays.sort(str1); //Arrays.sort() 需加包import java.util.*;或import java.util.Arrays Arrays.sort(str2); return Arrays.equals(str1, str2); //Returns true if the two specified arrays of chars are equal to one another }
Complexity analysis
Time complexity : O(n
\log n)O(nlogn).
Assume that nn is
the length of ss,
sorting costs O(n
\log n)O(nlogn) and
comparing two strings costs O(n)O(n).
Sorting time dominates and the overall time complexity is O(n
\log n)O(nlogn).
Space complexity : O(1)O(1).
Space depends on the sorting implementation which, usually, costs O(1)O(1) auxiliary
space if
heapsortis used. Note that in Java,
toCharArray()makes
a copy of the string so it costs O(n)O(n) extra
space, but we ignore this for complexity analysis because:
It is a language dependent detail.
It depends on how the function is designed. For example, the function parameter types can be changed to
char[].
pproach #2 (Hash Table) [Accepted]
AlgorithmTo examine if tt is
a rearrangement of ss,
we can count occurrences of each letter in the two strings and compare them. Since both ss and tt contain
only letters from a-za−z,
a simple counter table of size 26 is suffice.
Do we need two counter tables for comparison? Actually no, because we could increment the counter for each letter in ss and
decrement the counter for each letter intt,
then check if the counter reaches back to zero.
public boolean isAnagram(String s, String t) { if (s.length() != t.length()) { return false; } int[] counter = new int[26]; for (int i = 0; i < s.length(); i++) { counter[s.charAt(i) - 'a']++; //Returns the [code]charvalue at the specified index. An index ranges from
0to
length() - 1
counter[t.charAt(i) - 'a']--;
}
for (int count : counter) {
if (count != 0) {
return false;
}
}
return true;
}[/code]
Or we could first increment the counter for ss,
then decrement the counter for tt.
If at any point the counter drops below zero, we know that tt contains
an extra letter not in ss and
return false immediately
public boolean isAnagram(String s, String t) { if (s.length() != t.length()) { return false; } int[] table = new int[26]; for (int i = 0; i < s.length(); i++) { table[s.charAt(i) - 'a']++; } for (int i = 0; i < t.length(); i++) { table[t.charAt(i) - 'a']--; if (table[t.charAt(i) - 'a'] < 0) { return false; } } return true; }
Complexity analysis
Time complexity : O(n)O(n).
Time complexity is O(n)O(n) because
accessing the counter table is a constant time operation.
Space complexity : O(1)O(1).
Although we do use extra space, the space complexity is O(1)O(1) because
the table's size stays constant no matter how large nn is.
相关文章推荐
- 算法:字符串处理-判断两个字符串是否互为“形变词”(判断两字符串中字符种类和出现次数是否均相同)
- php面试题:如何知道一个未知长度的字符串哪个字符出现的次数最多?(字符串可由字母,数字及其他字符组成)请写出代码。
- 通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串过滤程序,若字符串中出现多个相同的字符,将非首次出现的字符过滤掉。
- 给定两个字符串newspaper和message,检查是否能够使用newspaper中的字母来组成message
- 对于给定的一个字符串,统计其中数字字符出现的次数。输入数据有多行,第一行是一个整数n,表示测试实例的个数,后面跟着n行,每行包括一个由字母和数字组成的字符串。
- 实现简易字符串压缩算法:一个长度最大为128的字符串, 由字母a-z或者A-Z组成,将其中连续出现2次以上(含2次)的字母转换为字母和出现次数,以达到压缩目的
- 判断两个字符串是否由相同字符组成
- 通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串过滤程序,若字符串中出现多个相同的字符,将非首次出现的字符过滤掉。
- 字典序问题。在数据加密和数据压缩中常需要对特殊的字符串进行编码。给定的字母表A由26个小写字母组成。该字母表产生的升序字符串中字母从左到右出现的次序与字母在字母表中出现的次序相同,且每个字符最多出现1
- Java寻找字符串中出现次数最多的字母和次数、两个字符串中寻找最长子字符串、字符串排序
- 字符串问题1:单词是否由相同字母组成
- [google面试CTCI] 1-4.判断两个字符串是否由相同字符组成
- 通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串过滤程序,若字符串中出现多个相同的字符,将非首次出现的字符过滤掉。
- 1.4-判断两个字符串是否由相同字符组成
- 判断两个字符串是否由相同的字符组成
- 将输入的字符串(字符串仅包含小写字母‘a’到‘z’),按照如下规则,循环转换后输出:a->b,b->c,…,y->z,z->a;若输入的字符串连续出现两个字母相同时,后一个字母需要连续转换2次。例如:
- 通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串过滤程序,若字符串中出现多个相同的字符,将非首次出现的字符过滤掉
- 判断两个字符串是否由相同的字符组成
- leetcode_318. Maximum Product of Word Lengths 求两个不相交的字符串的长度乘积的最大值,将字母转换成二进制形式,按位与比较是否有相同字母
- 通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串过滤程序,若字符串中出现多个相同的字符,将非首次出现的字符过滤掉。 比如字符串“abacacde”过滤结果为“abcde”。 要求实现函