[LintCode] Compare Strings
文章目录
Problem
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.
Note
建立一个长度为26的数组,每一位对应那个字母出现的个数,先遍历A,对数组做增操作,再遍历B,对数组做减操作。
Solution
public class Solution {
public boolean compareStrings(String A, String B) {
int[] count = new int[26];
for(int i = 0; i < A.length(); i++){
count[A.charAt(i) - 'A']++;
}
for(int i = 0; i < B.length(); i++){
count[B.charAt(i) - 'A']--;
if(count[B.charAt(i) - 'A'] < 0) {
return false;
}
}
return true;
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论