242. Valid Anagram

来源:互联网 发布:php 布尔型 编辑:程序博客网 时间:2024/05/16 17:09

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.

给定两个字符串,判断它俩是不是anagram。所谓anagram就是将一个字符串中的字符打乱顺序后得到的一个字符串。

思路:使用java的map类,存放s和t的字符到频数的映射关系。最后比较两个map返回结果。

public class Solution {    public boolean isAnagram(String s, String t) {        Map<Character,Integer> map = new HashMap<Character,Integer>();        Map<Character,Integer> map2 = new HashMap<Character,Integer>();        for(int i=0;i<s.length();i++){            char c = s.charAt(i);            if(map.containsKey(c))                map.put(c,map.get(c)+1);            else                map.put(c,1);        }        for(int i=0;i<t.length();i++){            char c = t.charAt(i);            if(map2.containsKey(c))                map2.put(c,map2.get(c)+1);            else                map2.put(c,1);        }        if(map.equals(map2))            return true;        else             return false;    }}
注意:java的原始类型(内置类型)与引用类型,map中必须使用封装类。

原始类型   封装类

boolean      Boolean

char           Character

byte           Byte

short          Short

int              Integer

long           Long

float           Float

double      Double


0 0