1.3 Whether Permutation
来源:互联网 发布:公司销售网络介绍 编辑:程序博客网 时间:2024/06/13 11:49
1.3 Given two strings, write a method to decide if one is a permutation of the other.
1. ask question
Whether the anagram comparison is case sensitive? Is whitespace significant?
Is God an anagram of dog? Is "god " is different from "odg"?
If two string have different lengths then they can't be anagrams.
2. Solution: sort the strings
If two strings are anagrams, they must have the same characters, but in different orders.
Sorting the strings will put the characters from two anagrams in the same order.
We just need to compare the sorted version of the strings.
This algorithm is clean and easy to understand but not very efficiency.
3. Solution: Check if the two strings have identical character counts
The definition of an anagram is two words with the same character counts.
We simply iterate through this code, counting how many times each character appears.
Then compare the two arrays.
class Permutation{ public static void main(String[] args){ String s1 = "abcb"; String s2 = "bbca"; permutation(s1,s2); permutation2(s1,s2); } public static void permutation(String str1, String str2){ if (str1.length() != str2.length()){ System.out.println("1.Not permutation of the other."); return; } if ( sort(str1).equals(sort(str2)) ) // sort s1 and s2 and compare System.out.println("1.Yes permutation of the other."); } public static String sort(String str){ // sort a string return a string char[] temp = str.toCharArray(); java.util.Arrays.sort(temp); // use JAVA sort return new String(temp); } public static void permutation2(String str1, String str2){ if (str1.length() != str2.length()){ System.out.println("2.Not permutation of the other."); return; } int[] check = new int[256]; // assumption if Unicode with a large array char[] temp = str1.toCharArray(); for (char c : temp) // count number of each char in temp check[c-'a']++; // careful with ArrayOutBound for (int i=0; i< str2.length(); i++){ int m = (int)str2.charAt(i); if (--temp[m-'a'] < 0){ System.out.println("2.Not permutation of the other."); return; } } System.out.println("2.Yes permutation of the other."); }}
- 1.3 Whether Permutation
- 1. PermCheck Check whether array A is a permutation.
- Permutation
- Permutation
- permutation
- Permutation
- Permutation
- Permutation
- permutation
- Permutation
- permutation
- Permutation
- Permutation
- permutation
- permutation
- permutation
- Permutation, next Permutation, Permutation sequence
- if和whether的区别
- java [数组]-[数组工具类]
- Zigbee扫盲
- 26、增强的for循环和自动装箱拆箱
- Android手机通过WIFI控制数码管
- IT人士必去的10个网站
- 1.3 Whether Permutation
- 网站导航
- POJ 3176
- Linux目录扫描:打印指定目录下的所有文件及目录
- [转] C++之父Bjarne Stroustrup写的《The C++ Programming Language (Special Edition)》中各章后面的忠告
- 关于帧缓存与OpenGL的帧缓存操作 glClearColor,glClear,glClearDepth
- 开源 免费 java CMS - FreeCMS-栏目页静态化参数
- 线性代数中的正则化(regularization)(zz)
- 关于虚拟打印机会改变程序目录的问题