#55 Compare Strings

題目描述:

Compare two strings A and B, determine whether A contains all of the characters in B.

The characters in string A and B are all Upper Case letters.

 Notice

The characters of B in A are not necessary continuous or ordered.

Example

For A = "ABCD"B = "ACD", return true.

For A = "ABCD"B = "AABC", return false.

題目思路:

這題我用了一種省space的方法:先把A和B排序,這樣我們就可以用two pointers的方法,一個一個從左到右比較了。

Mycode(AC = 19ms):

class Solution {
public:
    /**
     * @param A: A string includes Upper Case letters
     * @param B: A string includes Upper Case letter
     * @return:  if string A contains all of the characters in B return true 
     *           else return false
     */
    bool compareStrings(string A, string B) {
        // write your code here
        if (A.length() < B.length()) return false;
        if (B.length() == 0) return true;
        
        sort(A.begin(), A.end());
        sort(B.begin(), B.end());
        
        // traverse through A to see if each B's char
        // is in A
        int idx = 0;
        for (int i = 0; i < A.length(); i++) {
            if (B[idx] == A[i]) {
                idx++;
            }
        }
        
        return idx == B.length();
    }
};


發佈了221 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章