leetcode 242. Valid Anagram 颠倒字符的字符串的有效性判定 + HashMap
来源:互联网 发布:protobuf c windows 编辑:程序博客网 时间:2024/06/05 15:02
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.
最简单直接的方法就是直接HashMap统计即可。
代码如下:
import java.util.HashMap;/* * 注意使用Map数据结构 * */public class Solution { public boolean isAnagram(String s, String t) { if(s==null && t==null) return true; else if(s==null && t!=null || s!=null && t==null || s.length()!=t.length()) return false; HashMap<Character, Integer> map1=new HashMap<>(); HashMap<Character, Integer> map2=new HashMap<>(); for(int i=0;i<s.length();i++) { if(map1.containsKey(s.charAt(i))) map1.put(s.charAt(i), map1.get(s.charAt(i))+1); else map1.put(s.charAt(i), 0); if(map2.containsKey(t.charAt(i))) map2.put(t.charAt(i), map2.get(t.charAt(i))+1); else map2.put(t.charAt(i), 0); } return map1.equals(map2); }}
下面是C++的做法,就是使用一个26大小的数组纪录每一个字母出现的频率,也可以直接使用map做记录然后比较
代码如下:
#include <iostream>#include <alogrithm>#include <set>#include <map>#include <vector>#include <stack>#include <queue>using namespace std;class Solution {public: bool isAnagram(string s, string t) { vector<int> a(26,0); for (char i : s) a[i - 'a']++; for (char i : t) { a[i - 'a']--; if (a[i - 'a'] < 0) return false; } for (int i : a) { if (i > 0) return false; } return true; }};
阅读全文
0 0
- leetcode 242. Valid Anagram 颠倒字符的字符串的有效性判定 + HashMap
- [LeetCode] Valid Anagram 有效颠倒
- leetcode—242. Valid Anagram 判断由颠倒字母顺序而构成的词,python字典的应用
- LeetCode Valid Anagram 字符串
- [LeetCode][字符串]Valid Anagram
- (LeetCode)Valid Anagram --- 有效的混排字符串
- 242. Valid Anagram 有效的Anagram
- [leetcode] 242.Valid Anagram
- leetcode 242. Valid Anagram
- [leetcode] 242. Valid Anagram
- leetCode 242. Valid Anagram
- Leetcode 242. Valid Anagram
- 242. Valid Anagram LeetCode
- LeetCode 242. Valid Anagram
- LeetCode 242. Valid Anagram
- [LeetCode]242. Valid Anagram
- 【LeetCode】242. Valid Anagram
- leetcode 242. Valid Anagram
- BTrace安装和使用
- 泛型
- java代码获取Android客户端性能数据并写入Excel表
- redis资源包
- 2).静态代理VS动态代理
- leetcode 242. Valid Anagram 颠倒字符的字符串的有效性判定 + HashMap
- Cordova Error: Could not find an installed version of Gradle
- Centos7 开机自动启动服务
- 函数式编程笔记(三)——java8实践
- 初学JS小记(一)——变量的作用域
- JS中避免命名冲突
- 极光推送
- Spark Programming Guide(五)
- 求俩个数的和,要求不能用加减乘除四则运算。