博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LintCode/LeetCode] Two Strings are Anagrams/Valid Anagram
阅读量:6956 次
发布时间:2019-06-27

本文共 1832 字,大约阅读时间需要 6 分钟。

Program

Write a method anagram(s,t) to decide if two strings are anagrams or not.

Example

Given s="abcd", t="dcab", return true.

Challenge

O(n) time, O(1) extra space

Note

建立一个长度为256的数组,统计所有256个字符在String s出现的次数,然后减去这些字符在String t中出现的次数。若某个字符统计次数最终小于0,说明t中这个字符比s中更多,返回false。否则,循环结束,说明所有字符在st中出现的次数一致,返回true

Solution

Brute Force

O(nlogn)

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

HashMap

public class Solution {    public boolean anagram(String s, String t) {        int[] count = new int[256];        for (int i = 0; i < s.length(); i++) {            count[(int) s.charAt(i)]++;        }        for (int i = 0; i < s.length(); i++) {            count[(int) t.charAt(i)]--;            if (count[(int) t.charAt(i)] < 0) return false;        }        return true;    }}

Slow HashMap

public class Solution {    public boolean isAnagram(String s, String t) {        Map
map = new HashMap<>(); for (int i = 0; i < s.length(); i++) { Character ch = s.charAt(i); if (map.containsKey(ch)) { map.put(ch, map.get(ch)+1); } else map.put(ch, 1); } for (int i = 0; i < t.length(); i++) { Character ch = t.charAt(i); if (!map.containsKey(ch)) return false; map.put(ch, map.get(ch)-1); if (map.get(ch) < 0) return false; } for (int i = 0; i < s.length(); i++) { Character ch = s.charAt(i); if (map.get(ch) != 0) return false; } return true; }}

Follow up: contains unicode chars?

Just give the count[] array space of 256.

转载地址:http://lftil.baihongyu.com/

你可能感兴趣的文章
一个例子看懂所有nodejs的官方网络demo
查看>>
全文检索
查看>>
JSP三种常用注释
查看>>
iOS开发——高级技术&地图功能的实现
查看>>
SVN服务器搭建和使用(一)
查看>>
Android Studio 默认的快捷键
查看>>
FindWindow 查找窗口
查看>>
3027 线段覆盖 2
查看>>
JDBC处理文本和二进制文件
查看>>
菜单联动 加翻页
查看>>
GDB中打印ART基础类
查看>>
DFS-C
查看>>
POJ-2698-八皇后问题
查看>>
MySQL免安装版配置问题
查看>>
MySQL索引之B+树
查看>>
easyui中 combogrid控件的loadData方法加载本地数据
查看>>
Android实战技巧:消息循环与Looper
查看>>
android-audioRecord
查看>>
apache 访问权限基本设置
查看>>
jQuery的deferred对象详解
查看>>