LintCode(158)
来源:互联网 发布:linux 中文时间格式 编辑:程序博客网 时间:2024/06/02 03:57
两个字符串是变位词
写出一个函数 anagram(s, t)
去判断两个字符串是否是颠倒字母顺序构成的
样例
给出 s="abcd"
,t="dcba"
,返回ture
未采用数据结构的写法:
public class Solution { /** * @param s: The first string * @param t: The second string * @return true or false */ public boolean anagram(String s, String t) { // write your code here int a = s.length(); int b = t.length(); if (a != b){ return false; } for (int i = 0; i < a; i++){ char m = s.charAt(i); int num = 0; //标记值 for (int j = 0; j < a; j++){ if (t.charAt(j) == m){ num = 1; } } if (num == 1){ continue; } else { return false; } } return true; }};
此种解法实际是有错误的,比如"abbb"
,"baaa"
会被误认为是变位词,实际未然。
利用hash表对字符串存储,可得到理想的结果。代码如下:
import java.util.*;public class test{ public boolean compareStrings(String A, String B) { test cs = new test(); if(B.length() > A.length()) return false; Map<Character,Integer> aMap = cs.StringToMap(A); for(int i = 0; i < B.length(); i++){ char b = B.charAt(i); if (aMap.containsKey(b)){ if(aMap.get(b) > 1){ int times = aMap.get(b)-1; aMap.put(b, times); }else aMap.remove(b); }else return false; } return true;}public Map<Character,Integer> StringToMap(String S){ Map<Character,Integer> sMap = new HashMap<Character,Integer>(); for(int i = 0; i < S.length();i++){ char a = S.charAt(i); if(sMap.containsKey(a)){ int times = sMap.get(a)+1; sMap.put(a, times); }else sMap.put(a, 1); } return sMap;}public static void main(String []args){ test cst = new test(); boolean c = cst.compareStrings("aaadbb", "dbaaba"); System.out.print(c);}}
函数StringToMap
完成的功能是将字符串存储在hash表中,且返回一个对应的map映射。
比如StringToMap("lint")
,返回的map<Character,Integer>
映射为{t=1, n=1, l=1, i=1}
。 StringToMap("aaadbb")
返回的map
映射为{d=1,b=2,a=3}
;
(不过此处put函数为何按照字母从大到小放入到map中呢?不解) compareStrings()
的思路其实同StringToMap()
函数。
算法复杂度是O(n)
吧。
0 0
- LintCode(158)
- LintCode
- lintcode--
- lintcode
- LintCode
- Lintcode
- Lintcode - Median
- Lintcode - MedianII
- Lintcode - Heapify
- LintCode-组合
- LintCode 子树
- LintCode-加油站
- lintcode-422
- lintcode-189
- lintcode-103
- lintcode-384
- lintcode-423
- lintcode-子树
- Xcode7 使用NSURLSession发送HTTP请求的问题
- ZOJ 3380 Patchouli's Spell Cards 概率DP
- Linux常用命令
- JavaSE IO流 File文件操作基础知识
- HTTPS概述
- LintCode(158)
- 判断处理器是Big_endian的还是Little——endian的
- android ndk Using Prebuilt Libraries
- hdu 2955 Robberies
- 使用APKTOOL 反编译APK 失败的解决方法
- Hibernate插入、查询、删除操作 HQL
- Hash算法冲突解决方法分析
- 【扣丁学堂】看完惊呆!支付宝是如何用大数据憋死伪基站骗子?
- GIT和SVN之间的五个基本区别