[leetcode]Valid Anagram C语言
2015-08-29 15:23
316 查看
【题目】
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.
Note:
You may assume the string contains only lowercase alphabets.
【题目分析】
这道题就是判断s,t两个字符串里所含的每一种字母个数是否一样,一样,则返回true,不一样则返回false。采用的办法是用一个int check_s[26]来记录每个字母的个数。一次遍历,对于s中出现的字母,对应的check_s数组中元素加1,对于t中出现的字母,对应的check_s数组中元素减一,最后,判断check_s中所有元素是否全部是0,有非0,返回false,否则,返回true.
【具体代码如下】
【个人总结】
一开始,我是用了两个数组分别记录s,t中所含字母的情况。后来进一步思考,减小了空间使用。
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.
Note:
You may assume the string contains only lowercase alphabets.
【题目分析】
这道题就是判断s,t两个字符串里所含的每一种字母个数是否一样,一样,则返回true,不一样则返回false。采用的办法是用一个int check_s[26]来记录每个字母的个数。一次遍历,对于s中出现的字母,对应的check_s数组中元素加1,对于t中出现的字母,对应的check_s数组中元素减一,最后,判断check_s中所有元素是否全部是0,有非0,返回false,否则,返回true.
【具体代码如下】
bool isAnagram(char* s, char* t) { int check_s[26]={0}; int i; int indexs; int indext; for(i=0;(s[i]!='\0')||(t[i]!='\0');i++) { indexs=s[i]-'a'; check_s[indexs]++; indext=t[i]-'a'; check_s[indext]--; } for(i=25;i>=0;i--) { if(check_s[i]!=0) return false; } return true; }
【个人总结】
一开始,我是用了两个数组分别记录s,t中所含字母的情况。后来进一步思考,减小了空间使用。
相关文章推荐
- C++16个常用面试题
- C语言_为什么字符串可以赋值给字符指针变量,字符串的属性及存放位置
- c++ assert() 使用方法
- C++ vector用法
- 作业《IOS_C语言》函数分类、函数声明和定义、函数调用、形参实参、函数嵌套调用
- 【转载】高效排序——归并排序
- c++串口小结
- c++的声明与定义
- C++的头文件和实现文件分别写什么
- C语言基础(xcode)
- C++ sizeof 和strlen
- 【more effective c++读书笔记】【第3章】异常(2)
- 【more effective c++读书笔记】【第3章】异常(2)
- 《IOS_C语言》函数分类、函数声明和定义、函数调用、形参实参、函数嵌套调用
- c++静态库与动态库的区别
- 我的C++ primer plus第3章作业总结
- C语言内存分布(BSS段、数据段、代码段、堆与栈)
- C语言基础知识之(十二):结构体作为函数的参数(结构体变量、结构体数组)
- C语言基础知识之(十一):结构体的内存
- 在C语言编程中设置和获取代码组数的方法