Leetcode - Ransom Note

My code:

public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        if (ransomNote == null || magazine == null) {
            return false;
        }
        
        char[] c1 = ransomNote.toCharArray();
        char[] c2 = magazine.toCharArray();
        
        Arrays.sort(c1);
        Arrays.sort(c2);
        
        int p1 = 0;
        int p2 = 0;
        while (p1 < c1.length && p2 < c2.length) {
            if (c1[p1] == c2[p2]) {
                int counter1 = 1;
                p1++;
                while (p1 < c1.length && c1[p1] == c1[p1 - 1]) {
                    p1++;
                    counter1++;
                }
                int counter2 = 1;
                p2++;
                while (p2 < c2.length && c2[p2] == c2[p2 - 1]) {
                    p2++;
                    counter2++;
                }
                if (counter1 > counter2) {
                    return false;
                }
            }
            else {
                p2++;
            }
        }
        
        if (p1 < c1.length) {
            return false;
        }
        else {
            return true;
        }
    }
}

这道题目最简单的思路就是拿一个 hashmap之类的来技术,然后很容易就做出来了。
时间复杂度: O(m + n)
空间复杂度: O(n)

那么,有没有空间复杂度是 O(1)的解法呢?就是上面的解法
然后保持时间复杂度不变。双指针

Anyway, Good luck, Richardo! — 08/21/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/dede3487d493#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞