• *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.

    解法一: sort!

     
    public class Solution {
            public boolean isAnagram(String s, String t) {
                char[] schar = s.toCharArray();
                char[] tchar = t.toCharArray();
                Arrays.sort(schar);
                Arrays.sort(tchar);
                s = new String(schar);
                t = new String(tchar);
                return s.equals(t);
            }
        }

     解法二:hashmap

    import java.util.*;
    public class Solution {
        public boolean isAnagram(String s, String t) {
            if(s.length()!=t.length()) return false;
            
            Hashtable<Character, Integer> 
                theTableS = new Hashtable<Character, Integer>(),
                theTableT = new Hashtable<Character, Integer>();
            for (char i:s.toCharArray()) {
                if (theTableS.containsKey(i))
                    theTableS.put(i,theTableS.get(i)+1);
                else theTableS.put(i,1);
            }
            for (char i:t.toCharArray()) {
                if (theTableT.containsKey(i)) 
                    theTableT.put(i,theTableT.get(i)+1);
                else theTableT.put(i,1);
            }
            return theTableT.equals(theTableS);
        }
    }

     解法三:O(n) time, O(1) space

    public class Solution {
        public boolean isAnagram(String s, String t) {
            int[] alphabet = new int[26];
            for (int i = 0; i < s.length(); i++) alphabet[s.charAt(i) - 'a']++;
            for (int i = 0; i < t.length(); i++) alphabet[t.charAt(i) - 'a']--;
            for (int i : alphabet) if (i != 0) return false;
            return true;
        }
    }
  • 相关阅读:
    vue + ajax + php 接口的使用小接
    网页调用qq聊天
    基于touch.js 左滑删除功能
    touch.js——常见应用操作
    常用链接
    如何判断滚动条已到达底部
    前端如何优雅的选择字体
    纯css3打造瀑布流布局
    移动端软键盘监听(弹出,收起),及影响定位布局的问题
    jq获取图片的原始尺寸,自适应布局
  • 原文地址:https://www.cnblogs.com/hygeia/p/4858494.html
Copyright © 2020-2023  润新知