1. 程式人生 > >#158 Two Strings Are Anagrams

#158 Two Strings Are Anagrams

題目描述:

Write a method anagram(s,t) to decide if two strings are anagrams or not.

Have you met this question in a real interview?  Yes Clarification

What is Anagram?
- Two strings are anagram if they can be the same after change the order of characters.

Example

Given s = "abcd", t = "dcab"

, return true.
Given s = "ab", t = "ab", return true.
Given s = "ab", t = "ac", return false.

Challenge 

O(n) time, O(1) extra space

題目思路:

題目要求O(n) time, O(1) space,如果直接用map或者直接迴圈match兩次,都是不可行的。這裡發現,雖然string長度是無限的,可是用來表示characters的ASCII碼是有限的嘛!這裡可以建一個256 size的vector,將s中出現的ch按照次數填入vector中,而ch的index就是它對應的ASCII碼的int。再看t中的每一個ch有沒有一一對應即可。

Mycode (AC = 18ms):

class Solution {
public:
    /**
     * @param s: The first string
     * @param b: The second string
     * @return true or false
     */
    bool anagram(string s, string t) {
        // write your code here
        vector<int> chmap(256, 0);
        
        // if length not equal, then return false
        if (s.length() != t.length()) {
            return false;
        }
        
        // put s info into chmap
        for (int i = 0; i < s.length(); i++) {
            int intch = (int)(s[i]);
            chmap[intch] += 1;
        }
        
        // put t info into chmap
        for (int j = 0; j < t.length(); j++) {
            int intch = (int)(t[j]);
            chmap[intch] -= 1;
            if (chmap[intch] < 0) {
                return false;
            }
        }
        
        return true;
    }
};