Given two strings, write a method to decide if one is a permutation of the other.
Summary: We need to ask the interviewer if "a" is a permute of "A" and if all possible characters are in range of ASCII for this particular problem.
Solution 1:
First, we need to compare if two strings have the same size, if different then they can't be permutations of each other. Then we could sort two strings and compare if they are equal to each other.
Time Complexity: O(nlogn). Space Complexity: n (if we copy the input strings), 1 (if we alter the originals)
Solution 2:
As we discussed in problem 1.1, we could use additional space with size 256. This idea is extremely useful for string/character operation, because it could be considered as some kind of hash map that gives us O(1) access to each possible character (of course, we need to confirm with interviewer about the possible characters, see if it follows ACSII). We count the number of occurrences of each characters and store the result in additional space.
Time Complexity: O(n). Space Complexity: O(1) (constant space requirements)
Header file
#ifndef __QUESTION_1_3_H_CHONG__
#define __QUESTION_1_3_H_CHONG__
#include <string>
using namespace std;
class Question1_3 {
public:
bool isPermutation(string str1, string str2);
bool isPermutation_2(string& str1, string& str2);
int run();
};
#endif // __QUESTION_1_3_H_CHONG__
Source file
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include "Question1_3.h"
using namespace std;
bool Question1_3::isPermutation(string str1, string str2)
{
if (str1.size()==str2.size()) {
sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());
return str1==str2;
}
else return false;
}
bool Question1_3::isPermutation_2(string& str1, string& str2)
{
if (str1.size()==str2.size()) {
int cnts[256] = {0};
for (int i=0; i<str1.size(); ++i) {
cnts[int(str1[i])]++;
}
for(int i=0; i<str2.size(); ++i) {
cnts[int(str2[i])]--;
if (cnts[int(str2[i])]<0) {
return false;
}
}
return true;
}
else return false;
}
int Question1_3::run() {
string str1 = "Hello";
string str2 = "Heoll";
string str3 = "Coell";
if (isPermutation(str1, str2)) {
cout << str2 << " is a permutation of " << str1 << endl;
}
if (!isPermutation_2(str3, str1)) {
cout << str3 << " is not a permutation of " << str1 << endl;
}
return 0;
}