242. Valid Anagram(两个字符串包含的字符是否完全相同)

本文介绍两种方法来判断两个字符串是否为字谜变位词:使用哈希表记录字符频率和通过快速排序比较排序后的字符串。这两种方法适用于只包含小写字母的字符串,并探讨了如何处理包含Unicode字符的情况。

Given two strings s and , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

解释:首先简单介绍一下Anagram(回文构词法)。Anagrams是指由颠倒字母顺序组成的单词,比如“dormitory”颠倒字母顺序会变成“dirty room”,“tea”会变成“eat”。回文构词法有一个特点:单词里的字母的种类和数目没有改变,只是改变了字母的排列顺序。

方法一:哈希表

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.toCharArray().length!=t.toCharArray().length)
            return false;
        HashMap<Character,Integer> map=new HashMap<Character,Integer>();
        for(char c:s.toCharArray()){
            if(map.containsKey(c)){
                int nums=map.get(c);
                map.put(c,nums+1);
            }else{
                map.put(c,1);
            }
            
        }
        for(char c:t.toCharArray()){
            if(!map.containsKey(c)){
                return false;
            }
            int nums=map.get(c);
            if(nums==1){
                map.remove(c);
            }else{
                nums--;
                map.put(c,nums);
            }

        }
        return true;
    }
}

 

方法二:快排

先对每个数组排序,再比较是否一样。

 

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.toCharArray().length!=t.toCharArray().length)
            return false;
        char[] cs=s.toCharArray();
        char[] ct=t.toCharArray();
        quickSort(cs,0,cs.length-1);
        quickSort(ct,0,ct.length-1);
        
        for(int i=0;i<cs.length;i++){
            if(cs[i]!=ct[i])
                return false;
        }
        return true;
    }
    private void quickSort(char[] array,int low,int high){
        int i,j;
        char t,temp;
        if(low>high) return ;
        i=low;
        j=high;
        temp=array[low];
        while(i<j){
            while(temp<=array[j]&&i<j)  j--;
            while(temp>=array[i]&&i<j)  i++;
            if(i<j){
                t=array[i];
                array[i]=array[j];
                array[j]=t;
            }
        }
        array[low]=array[j];
        array[j]=temp;
        quickSort(array,low,j-1);
        quickSort(array,j+1,high);
    }
}

 

转载于:https://www.cnblogs.com/shaer/p/10846912.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值