(1) inflected word

topic:

  • Determine whether two strings are inflected words

Description:
Given two character strings str1 and str2, if the type and number of characters contained in the two character strings are the same, call these two inflected words
Example:
str1 = "123"; str2 = "321"; return true
str1 = "123"; str2 = "223"; return false

Ideas:

  • If the two strings are different in length, then the two strings cannot be inflected words
  • Create an array map [255] to record the number of occurrences of each character, and use the position of the character in the ASCII table as a subscript index in the data;
  • Traverse one of the strings, record the number of occurrences of all characters, and accumulate the number of occurrences of the map map [i] ++;
  • Traverse the second string, and decrement the count of the characters encountered in the map array map [i] –;
  • If the two strings are inflected each other, then the count in the last map data should be all 0; and if they are not inflected each other, then the count in the map must not be all 0, some may be greater than 0, and some are less than 0.

Code:

The following is a legal format:
int map [100] = {0};
map ['a'] = 2;

/*
*	author : sunzd
*	date   : 2019-12-24
*   city   : beijing
*   
*/
#include <stdio.h>
#include <string.h>
#define TRUE  1
#define FALSE 0
int isDeformation(const char *str1, const char *str2)
{
	int map[255] = {0};
	int i = 0;
	int len;

	if(!str1 || !str2 || strlen(str1)!=strlen(str2)){
		return FALSE; 
	}
	len = strlen(str1);
	for(i=0;i<len;i++){
		map[str1[i]]+=1;
		map[str2[i]]-=1;
	}

	for(i=0;i<255;i++){
		if(map[i]!=0){
			return FALSE;
		}
	}
	return TRUE;
}
/*改进*/
int isDeformation_A(const char *str1, const char *str2)
{
	int map[255] = {0};
	int i = 0;
	int len;

	if(!str1 || !str2 || strlen(str1)!=strlen(str2)){
		return FALSE; 
	}
	len = strlen(str1);
	for(i=0;i<len;i++){
		map[str1[i]]++;
	}
	for(i=0;i<len;i++){
		map[str2[i]]--;
		if(map[str2[i]] < 0)
			return FALSE;
	}
	return TRUE;
}
81 original articles published · Liked 69 · Visitors 50,000+

Guess you like

Origin blog.csdn.net/s2603898260/article/details/103707146