Check Permutation
For a given two strings, 'str1' and 'str2', check whether they are a permutation of each other or not.
Permutations of each other
Input Format:
Note:
Output Format:
Constraints:
Sample Input 1:
Sample Output 1:
Sample Input 2:
Sample Output 2:
#include <iostream>
#include <cstring>
using namespace std;
#include "solution.h"
#include <bits/stdc++.h>
bool isPermutation(char str1[], char str2[]){
// Create 2 count arrays and initialize
// all values as 0
int count1[256] = {0};
int count2[256] = {0};
int i;
// For each character in input strings,
// increment count in the corresponding
// count array
for (i = 0; str1[i] && str2[i]; i++)
{
count1[str1[i]]++;
count2[str2[i]]++;
}
// If both strings are of different length.
// Removing this condition will make the
// program fail for strings like "aaca"
// and "aca"
if (str1[i] || str2[i])
return false;
// Compare count arrays
for (i = 0; i < 256; i++)
if (count1[i] != count2[i])
return false;
return true;
}
int main() {
int size = 1e6;
char str1[size];
char str2[size];
cin >> str1 >> str2;
cout << (isPermutation(str1, str2) ? "true" : "false");
}
////////////////////////////////////////////////////////////////////////
bool isPermutation(char input1[], char input2[]) {
// Write your code here
int freq[256]={0};
if(strlen(input1)!=strlen(input2)){
return false;
}
else{
for(int i=0;i<strlen(input1);i++){
int ascii=input1[i];
freq[ascii]++;
}
for(int i=0;i<strlen(input2);i++){
int ascii=input2[i];
freq[ascii]--;
}
for(int i=0;i<256;i++){
if(freq[i]!=0){
return false;
}
}
return true;
}
}
Comments
Post a Comment