Using Hash Set to Determine if a String is the Permutation of An

  • 时间:2020-09-09 13:08:38
  • 分类:网络文摘
  • 阅读:112 次

Given two strings s1 and s2, write an algorithm to determine if s1 is one permutation of s2.

For example:
s1 = “abc”, s2 = “bca”
output: true

s1 = “abc”, s2 = “bad”
output: false

Algorithm to Determine if a String is the Permutation of Another String

The fastest way to determine this is to use hash sets. If both strings (s1 and s2) are of different sizes, the result has to be false. Otherwise, we can convert both into two hash sets and simply compare the equality of both hash sets.

In C++, you can directly compare the the equality of both hash sets, either set (based on Red-Black Tree) or unordered_set (based on Hash Map):

1
2
3
4
5
6
7
8
9
class Solution {
public:
    bool CheckPermutation(string s1, string s2) {
        if (s1.size() != s2.size()) return false;
        unordered_set<char> a(begin(s1), end(s1));
        unordered_set<char> b(begin(s2), end(s2));
        return a == b;
    }
};
class Solution {
public:
    bool CheckPermutation(string s1, string s2) {
        if (s1.size() != s2.size()) return false;
        unordered_set<char> a(begin(s1), end(s1));
        unordered_set<char> b(begin(s2), end(s2));
        return a == b;
    }
};

Using unordered_set in C++, you will have a O(N) complexity however if you are using set (which keeps the keys in order by tree), the complexity is O(N.Log(N)).

In Python, we can do the same, with less code:

1
2
3
4
5
class Solution:
    def CheckPermutation(self, s1: str, s2: str) -> bool:
        if len(s1) != len(s2):
            return False
        return set(s1) == set(s2)
class Solution:
    def CheckPermutation(self, s1: str, s2: str) -> bool:
        if len(s1) != len(s2):
            return False
        return set(s1) == set(s2)

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
维生素C缺乏症的主要表现及其治疗  素食有哪些误区素食者需要注意的问题  素食的分类及适当素食具有的保健作用  冬季咳嗽吃什么自制美味止咳小零食  冬季进补鸡汤要注意 几类人不宜喝鸡汤  芦荟的保健价值、食用禁忌及食用方法  冬季食疗养生:吃南瓜可有效治疗哮喘  食疗:有效增强男人性能力的八款药膳  枸杞保健食疗功效多补肾益精养肝明目  如何从感官上辨别枸杞的真假和质量优劣 
评论列表
添加评论