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 Caseletters.
ExampleFor A = "ABCD", B = "ABC", return true.
For A = "ABCD" B = "AABC", return false.
public boolean compareStrings(String A, String B) {
if (A == null || B == null) {
return false;
}
if (A.length() < B.length()) {
return false;
}
if (A.length() >= 0 && B.length() == 0) {
return true;
}
boolean[] visited = new boolean[A.length()];
for (int i = 0; i < visited.length; i++) {
visited[i] = false;
}
int count = 0;
for (int i = 0; i < B.length(); i++) {
for (int j = 0; j < A.length(); j++) {
if (B.charAt(i) == A.charAt(j) && !visited[j]) {
count++;
if (count == B.length()) {
return true;
}
visited[j] = true;
break;
}
}
}
return false;
}思路:
O(n^2)遍历,consumable 用visited标志。
本文介绍了一种用于判断字符串A是否包含字符串B所有字符的算法。该算法通过使用布尔数组标记已匹配字符,避免了重复匹配同一字符的问题。适用于全部由大写字母组成的字符串对比场景。
1021

被折叠的 条评论
为什么被折叠?



