GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

How to decide if a string is a permutation of another string

Given two strings,write an algorithm to decide if one string is permutation of another.

asked Apr 6 by Ranju Kumari

1 Answer

Hii....

I have solved this problem in C++ by using simple logical approach and with minimum time complexity.

It prints TRUE if a string is permutation of another string and prints FALSE if a string is not a permutation of another.

You can change the values of both strings (basically a char array) then you can check that a string is permutation of another string or not. 

I have hard coded both the strings but you can try it by taking console input too.

 

#include<iostream>

using namespace std;

bool isPermutation( char str1[] , char str2[] )
{
	int myCounter[128] = {0};
	
	int len1 = 0;
	for( ; str1[len1] != '\0' ; len1++ );
	
	int len2 = 0;
	for( ; str2[len2] != '\0' ; len2++ );
	
	if( len1 != len2 )
		return false;
		
	for( int i = 0 ; i < len1 ; i++ )
	{
		myCounter[str1[i]]++;
		myCounter[str2[i]]--;
	}
	
	for( int i = 0 ; i < 127 ; i++ )
		if( myCounter[i]!=0 )
			return false;
	
	return true;
	
}

int main()
{
	char str1[] = "ABCDE";
	char str2[] = "BCDEA";
	
	if( isPermutation( str1 , str2 ) )
		cout << "TRUE";
	else
		cout << "FALSE";
	return 0;
}

For any suggestions or problem you can contact on chasta.vipul@gmail.com

answered Apr 17 by vipulchasta
...