158.Two Strings Are Anagrams-两个字符串是变位词(容易题)
来源:互联网 发布:近年来重庆物流数据 编辑:程序博客网 时间:2024/04/30 17:19
两个字符串是变位词
题目
写出一个函数 anagram(s, t) 判断两个字符串是否可以通过改变字母的顺序变成一样的字符串。
样例
给出 s = “abcd”,t=”dcab”,返回 true.
给出 s = “ab”, t = “ab”, 返回 true.
给出 s = “ab”, t = “ac”, 返回 false.题解
本题中字符串由大小写字母构成,则构建一个长度为52的数组。然后在遍历第一个字符串时计算出每个字母的个数,在遍历第二个字符串时在数组中依次减去所含的字符的个数。如果两个字符串是变位词,则数组元素应全部为0,时间复杂度为O(n)。
public class Solution { /** * @param s: The first string * @param b: The second string * @return true or false */ public boolean anagram(String s, String t) { int[] arr = new int[52]; for (int i=0;i<s.length();i++) { if (s.charAt(i) >= 'a' && s.charAt(i) <= 'z') { arr[s.charAt(i)-'a']++; } else if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') { arr[s.charAt(i)-'A' + 26]++; } } for (int j=0;j<t.length();j++) { if (t.charAt(j) >= 'a' && t.charAt(j) <= 'z') { arr[t.charAt(j)-'a']--; } else if (t.charAt(j) >= 'A' && t.charAt(j) <= 'Z') { arr[t.charAt(j)-'A' + 26]--; } } for (int k=0;k<arr.length;k++) { if (arr[k] != 0) { return false; } } return true; }};
Last Update 2016.9.7
0 0
- 158.Two Strings Are Anagrams-两个字符串是变位词(容易题)
- LintCode Two Strings Are Anagrams 两个字符串是变位词
- Two Strings Are Anagrams
- Two Strings Are Anagrams
- Two Strings Are Anagrams
- Two Strings Are Anagrams
- Two Strings Are Anagrams-LintCode
- #158 Two Strings Are Anagrams
- 两个字符串是变位词
- 两个字符串是变位词
- 两个字符串是变位词
- 两个字符串是变位词
- 两个字符串是变位词
- 两个字符串是变位词
- 两个字符串是变位词
- [Amazon] Two Strings Are Anagrams (Compare Strings)
- Lintcode158 Two Strings Are Anagrams solution 题解
- Lintcode—(1)两个字符串是变位词
- JavaScript 变量、作用域和内存问题
- 面向对象_工具类中使用静态
- Oracle中创建dblink的方法
- 二分查找或插入
- android中确定键重复点击,却只想在时间内,只显示点击一次
- 158.Two Strings Are Anagrams-两个字符串是变位词(容易题)
- Appium 基础概念
- 新开始,java基础小结
- android多进程通信的几种方式一
- Appium - WebView测试(Android)
- PAT How Long Does It Take (25) (拓扑排序)
- 原串翻转
- 数据结构学习记录-1
- 全局变量赋值问题