首页 > 代码库 > CTCI 1.3

CTCI 1.3

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

We could use the same idea from CTCI 1.1. The only difference is that in 1.1 we just need to know whether one character appear or not, in this problem we need to count its apperance. Since we could use additional data structure, I adopt HashMap to implement the algorithm. If the string is ASCII, we could use array instead, too. Firstly, if the two string‘s length does not match, return false, else iterate the first string, record each character and its number of apperance and then iterate the other string, if a given character is not contained, return false, else minus the corresponding number, if the number reduces to 0, remove the entry from the HashMap. At last, return true.

/* If the length of two string does not equal, return false;    Else use a HashMap to count the character and its corresponding number    Iterate the other string, if one character does not appear, return false;    Else just minus the numbre by one    if the number is 0, remove the corresponding entery    At last, check if the HashMap is null, if not, return false;    Else return true; */import java.util.*;public class IsPermutation {    public boolean isPermutation(String s1, String s2) {        if(s1.length() != s2.length()) return false;        HashMap<Character, Integer> map = new HashMap<Character, Integer>();        for(int i = 0; i < s1.length(); i++) {            char ch = s1.charAt(i);            if(map.containsKey(ch) == false) {                map.put(ch, 1);            }            else {                map.put(ch, map.get(ch)+1);            }        }        for(int i = 0; i < s2.length(); i++) {            char ch = s2.charAt(i);            if(map.containsKey(ch) == false) return false;            else {                map.put(ch, map.get(ch)-1);                if(map.get(ch) == 0) map.remove(ch);            }        }        //if(map.size() != 0) return false;        return true;    }    public static void main(String[] args) {        IsPermutation ip = new IsPermutation();        System.out.println(ip.isPermutation("", ""));        System.out.println(ip.isPermutation("aa", "a"));        System.out.println(ip.isPermutation("babaa", "bbaaa"));        System.out.println(ip.isPermutation("abc", "abd"));    }}

The time complexity and space complexity both are O(N). If we are allowed to destroy the original strings, we could sort the string, and compare each character one by one. This could use no extra space determined by the sort algorithm chosen but the time complexity would be O(NlogN).