1. 程式人生 > >211. String Permutation【LintCode by java】

211. String Permutation【LintCode by java】

char article target col tco csdn tle line XA

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

解題:遇到過類似的題目,比較簡單的方法是,把字符串轉化為字符數組,然後排序、比較每一位的數是否相等。這樣做效率比較低,代碼如下:

 1 public class Solution {
 2     /**
 3      * @param
A: a string 4 * @param B: a string 5 * @return: a boolean 6 */ 7 public boolean Permutation(String A, String B) { 8 // write your code here 9 if(A.length() != B.length()) 10 return false; 11 char[]a = A.toCharArray(); 12 char[]b = B.toCharArray();
13 Arrays.sort(a); 14 Arrays.sort(b); 15 for(int i = 0; i < a.length; i++){ 16 if(a[i] != b[i]) 17 return false; 18 } 19 return true; 20 } 21 }

也可以通過哈希表來做:如果每個元素的個數都相等,並且總個數相同,則字符串完全相等,參考:https://blog.csdn.net/wutingyehe/article/details/51212982。

211. String Permutation【LintCode by java】