211. String Permutation【LintCode by java】

时间:2023-12-27 14:05:07

Description

Given two strings, write a method to decide if one is a permutation of the other.

Example

abcd is a permutation of bcad, but abbe is not a permutation of abe

解题:遇到过类似的题目,比较简单的方法是,把字符串转化为字符数组,然后排序、比较每一位的数是否相等。这样做效率比较低,代码如下:

 public class Solution {
/**
* @param A: a string
* @param B: a string
* @return: a boolean
*/
public boolean Permutation(String A, String B) {
// write your code here
if(A.length() != B.length())
return false;
char[]a = A.toCharArray();
char[]b = B.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
for(int i = 0; i < a.length; i++){
if(a[i] != b[i])
return false;
}
return true;
}
}

也可以通过哈希表来做:如果每个元素的个数都相等,并且总个数相同,则字符串完全相等,参考:https://blog.csdn.net/wutingyehe/article/details/51212982