zoukankan      html  css  js  c++  java
  • LeetCode 242. 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.

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

    题意:给定两个字符串s和t,判断s和t是否为相同字母的异序词
    例:s = "anagram", t = "nagaram", 返回 true.
    s = "rat", t = "car",返回 false.
    note:
    假设字符串只包含小写字母
    follow up:
    如果字符串中含有特殊字符

    思路:将字符串s和t存入字符数组中,然后将数组排序,逐个比较数组中的字符。也可用于特殊字符的处理

    public boolean isAnagram(String s, String t) {
            char[] chars1 = s.toCharArray();
            char[] chars2 = t.toCharArray();
            int len1 = chars1.length;
            int len2 = chars2.length;
            if(len1 != len2)
                return false;
            Arrays.sort(chars1);
            Arrays.sort(chars2);
            for(int i = 0; i < len1; i++){
                if(chars1[i] != chars2[i])
                    return false;
            }
            return true;
        }

    LeetCode提供的方法更简洁。用Arrays的equals方法,直接比较两个数组是否相等。

    public boolean isAnagram(String s, String t){
            if(s.length() != t.length())
                return false;
            char[] chars1 = s.toCharArray();
            char[] chars2 = t.toCharArray();
            Arrays.sort(chars1);
            Arrays.sort(chars2);
            return Arrays.equals(chars1, chars2);
        }

    思路2:定义一个26个元素的数组,将s.charAt(i) - 'a'作为数组下标,遍历字符串中的字符,s中的字符让数组对应下标的元素加1,t中的字符让数组对应下标的元素减1,

    然后遍历数组,如果存在不为0的元素,则返回false。

    public boolean isAnagram(String s, String t){
            if(s.length() != t.length())
                return false;
            int[] num = new int[26];
            for(int i = 0; i < s.length(); i++){
                num[s.charAt(i) - 'a']++;
                num[t.charAt(i) - 'a']--;
            }
            for(int i : num){
                if(i != 0)
                    return false;
            } 
            return true;
        }

    改进:

    public boolean isAnagram(String s, String t){
            if(s.length() != t.length())
                return false;
            int[] num = new int[26];
            for(int i = 0; i < s.length(); i++){
                num[s.charAt(i) - 'a']++;
            }
            for(int i = 0; i < t.length(); i++){
                num[t.charAt(i) - 'a']--;
                if(num[t.charAt(i) - 'a'] < 0)
                    return false;
            }
            return true;
        }
  • 相关阅读:
    [luogu p2482] [SDOI2010]猪国杀
    [luogu p2296] 寻找道路
    左右布局(备用复制)
    导出Excel
    流式布局 及 媒体查询
    echarts设置(持续更新)
    解决Vue中watch首次进入路由不触发的问题
    Math.random
    Vue的拖拽
    使的dialog上下左右居中(弹框居中)
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/8571924.html
Copyright © 2011-2022 走看看