有效的字母异位词

题目来源于力扣–https://leetcode-cn.com/

查找字符串中每个字符出现的次数,如果每个字符出现的次数是一样多的,那就返回true,否则返回false。出现的字符都是小写,因为小写字母ASCII码是数字,字符也是可以排序的,这种情况下首先判断两个字符串的长度是否一致,长度不一致,直接返回false,如果长度一致就进行快速排序,在判断每个字符串的每个位置的字符是否相等,如果相等返回true,否则返回false。

main函数代码

#include<stdio.h>
void quickSort(char* nums,int begin,int end);
bool isAnagram(char * s, char * t);
int main(){
	char s[] = "ab";
	char t[] = "a";
	bool isTrue = isAnagram(s,t);
	printf("%d",isTrue);
	return 0;
}

判断代码

bool isAnagram(char * s, char * t){
	// 判断字符串长度
	int count_s = 0;
	int count_t = 0;
	while(s[count_s]){
		count_s++;
	}
	while(t[count_t]){
		count_t++;
	}
	// 如果长度不同 直接返回
	if(count_s!=count_t){
		return false;
	}
	 // 排序代码
	quickSort(s,0,count_s-1);
	quickSort(t,0,count_s-1);
	// 比较每个字符
	for(int j=0;j<count_s;j++){
		if(s[j]!=t[j]){
			return false;
		}
	}
	return true;
}

快速排序

void quickSort(char* nums,int begin,int end){
	if(begin>=end){
		return;
	}
	// 首先选择基准位置 
	int low = begin;
	// 将该元素保存起来,备用,否则会被覆盖
	int temp = nums[low];
	// 指向数组最后一个位置 
	int high = end; 
	// 当low==high 表示基准位置找到了,第一次快排已经完成了。 
	while(low<high){
		// 此时说明a[high]>temp,然后向前走,继续找。 
		while(low<high&&nums[high]>temp){
			high--;
		}
		// 跳出上边的循环后,表示遇到了比基准元素小的元素,将a[low] = a[high] 
		if(low<high){
			nums[low++] = nums[high];
		}
		// 然后从左边开始继续寻找,temp>a[low],然后往后走,继续找 
		while(low<high&&nums[low]<temp){
			low++;
		} 
		// 跳出上边的循环后说明 a[high]<a[low],将a[high] = a[low] 
		if(low<high){
			nums[high--] = nums[low];
		}
	}
	// 整个循环完成后,表示low==high了,这个位置就是一开始选择的基准元素的位置
	nums[low] = temp;
	// 基准元素一分为二,左边的都是比它小的,右边的都是比它大的,递归急继续解决
	// 解决左部分 
	quickSort(nums,begin,low-1);
	// 解决右部分 
	quickSort(nums,low+1,end);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值