面试题 01.02

Given two strings,write a method to decide if one is a permutation of the other.

Example 1:

Input: s1 = "abc", s2 = "bca" Output: true Example 2:

Input: s1 = "abc", s2 = "bad" Output: false Note:

0 <= len(s1) <= 100 0 <= len(s2) <= 100

Solutions

  1. hash map

class Solution {
public:
    bool CheckPermutation(string s1, string s2) {
        if (s1.size() != s2.size()) return false;
        vector<int> count(26);

        for (int i = 0; i < s1.size(); i++) {
            count[s1[i] - 'a']++;
            count[s2[i] - 'a']--;
        }
        for (auto c : count) if (c) return false;

        return true;
    }
};

Last updated

Was this helpful?