资讯专栏INFORMATION COLUMN

[LintCode] Compare Strings

avwu / 541人阅读

摘要:建立一个长度为的数组,每一位对应那个字母出现的个数,先遍历,对数组做增操作,再遍历,对数组做减操作。

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;    
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65950.html

相关文章

  • [LintCode] Nuts & Bolts Problem

    Problem Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Comparison of a nut to another nut or a bolt to another bolt is not ...

    tuomao 评论0 收藏0
  • [LintCode/LeetCode] Two Strings are Anagrams/Valid

    摘要:建立一个长度为的数组,统计所有个字符在出现的次数,然后减去这些字符在中出现的次数。否则,循环结束,说明所有字符在和中出现的次数一致,返回。 Program Write a method anagram(s,t) to decide if two strings are anagrams or not. Example Given s=abcd, t=dcab, return true....

    vslam 评论0 收藏0
  • [LeetCode/LintCode] Top K Frequent Words

    LeetCode version Problem Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, t...

    0x584a 评论0 收藏0
  • [LintCode] Kth Smallest Number in Sorted Matrix

    Problem Find the kth smallest number in at row and column sorted matrix. Example Given k = 4 and a matrix: [ [1 ,5 ,7], [3 ,7 ,8], [4 ,8 ,9], ] return 5 Challenge O(k log n), n is the maximal n...

    mgckid 评论0 收藏0
  • [LintCode/LeetCode] Find Median From / Data Stream

    摘要:建立两个堆,一个堆就是本身,也就是一个最小堆另一个要写一个,使之成为一个最大堆。我们把遍历过的数组元素对半分到两个堆里,更大的数放在最小堆,较小的数放在最大堆。同时,确保最大堆的比最小堆大,才能从最大堆的顶端返回。 Problem Numbers keep coming, return the median of numbers at every time a new number a...

    zxhaaa 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<