题目描述:
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();
}
};