LeetCode-Valid Anagram
Posted IncredibleThings
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-Valid Anagram相关的知识,希望对你有一定的参考价值。
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.
public class Solution { public boolean isAnagram(String s, String t) { if(s.length() != t.length()){ return false; } HashMap<Character, Integer> map=new HashMap<Character, Integer>(); for(int i=0; i<s.length(); i++){ char c=s.charAt(i); if(map.containsKey(c)){ int count=map.get(c)+1; map.put(c, count); } else{ map.put(c,1); } } for(int i=0; i<t.length(); i++){ char c=t.charAt(i); if(map.containsKey(c)){ int count=map.get(c)-1; map.put(c,count); } else{ return false; } } for(Character c : map.keySet()){ if(map.get(c)!=0){ return false; } } return true; } }
以上是关于LeetCode-Valid Anagram的主要内容,如果未能解决你的问题,请参考以下文章