[242] Valid Anagram
来源:互联网 发布:因特网属于什么网络 编辑:程序博客网 时间:2024/05/17 03:14
1. 题目描述
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.
题目意思为判定两个字符串是否为同字母异序词,根据例子来看,同字母异序词表示所包含字母相同但排列次序不同的两个单词,另外题目假定两个单词都只使用小写字母。
2. 解题思路
题目的关键在于两个点,①同字母②异序
包含字母是否相同我想到的是统计词频,若每个字母出现的频率相同而两个单词又不相同则两个单词为同字母异序词,在这里我使用的判断词频是否相等的方法是创建一个一维数组包含26个位置,对s和t进行一次遍历,过程如下图,当遍历完成后数组所有元素为0,即为词频相同。
边界条件
这里有一些边界是我一开始没有想到的,包括①两个字符串为空时②两个字符串都是只有一个字母并且相同时,都满足同字母异序
3. Code
class Solution {public: bool isAnagram(string s, string t) { if(s == "" && t == "") // s=t=空 return true; // s=t='a' if(s == t && s.length() == 1 && t.length() == 1) return true; else if(s == t) // s与t完全相等 return false; else if(s.length() != t.length()) // s与t长度不同 return false; else { int* statistic = new int[26]; // 保存词频 // 初始化statistic全为0 for(int init(0); init < 26 ; ++init) { statistic[init] = 0; } for(int i(0); i<s.length(); ++i) { statistic[s[i]-'a']++; // 对应位置+1 statistic[t[i]-'a']--; // 对应位置-1 } // 若s,t词频相等则statistic全为0 for(int j(0); j < 26; ++j) { if(statistic[j] != 0){ delete[] statistic; return false; } } delete[] statistic; return true; } }};
0 0
- Leetcode #242 Valid Anagram
- leetcode-242-Valid Anagram
- leetcode 242: Valid Anagram
- 242-e-Valid Anagram
- 【LeetCode】242 Valid Anagram
- 242-Valid Anagram
- 242 Valid Anagram
- 242 Valid Anagram
- [leetcode 242]Valid Anagram
- leetCode #242 Valid Anagram
- Leetcode #242 Valid Anagram
- LeetCode 242 Valid Anagram
- [242] Valid Anagram
- [LeetCode 242] Valid Anagram
- LeetCode(242)Valid Anagram
- leetcode[242] Valid Anagram
- leetcode 242 :Valid Anagram
- [242]Valid Anagram
- 凸包,旋转卡壳模板
- c++中static总结
- MAC环境下生成Apple证书教程
- Windows Server 2003 终止服务后的一个月,想它想它想它...
- 鼠标移上去出现显示层,并且出现在同一个div中
- [242] Valid Anagram
- AC自动机模板(数组实现版)
- 程序员的几个成长阶段
- 在线支付开发流程总结<包括客户端与服务端>
- 天柳投资股份有限公司大连分公司-面试总结
- streamflow简介
- http post get 区别
- 阿里巴巴一道笔试题
- iOS项目开发实战——使用用户首选项数据API存储信息