Lintcode—(3)比较字符串
来源:互联网 发布:java核心技术 pdf 编辑:程序博客网 时间:2024/04/27 22:52
比较两个字符串A和B,确定A中是否包含B中所有的字符。字符串A和B中的字符都是 大写字母
注意事项
在 A 中出现的 B 字符串里的字符不需要连续或者有序。
样例
给出 A = "ABCD"
B = "ACD"
,返回 true
给出 A = "ABCD"
B = "AABC"
, 返回 false
解法一:
public class Solution { /** * @param A : A string includes Upper Case letters * @param B : A string includes Upper Case letter * @return : if string A contains all of the characters in B return true else return false */ public boolean compareStrings(String A, String B) { // write your code here int[] index = new int[26]; for(int i = 0; i < A.length();i++){ index[A.charAt(i) - 'A']++; } for(int i = 0; i < B.length();i++){ index[B.charAt(i) - 'A']--; if(index[B.charAt(i) - 'A'] < 0){ return false; } } return true; }}
解题思路:
和解法二本质一样。首先定义一个值为0,长度为26的int数组。index[A.charAt(i) - 'A']++; 这句代码先将26个字母与数组索引一一对应,然后根据索引将对应位置的值加1。同样的方法遍历B字符串,如果A、B两个字符串相同则数组的值会全部为0,如果B中有A中不存在的则会出现负数。A中有B中不存在的,则会出现正数。
解法二:
public class Solution { /** * @param A : A string includes Upper Case letters * @param B : A string includes Upper Case letter * @return : if string A contains all of the characters in B return true else return false */ public boolean compareStrings(String A, String B) { // write your code here Map<String, Integer> map = new HashMap<String, Integer>(); for (int i = 0; i < 26; i++) { map.put((char)(i + 'A') + "", 0); } for (int i = 0; i < A.length(); i++) { String key = A.charAt(i) + ""; Integer count = map.get(key); map.put(key, ++count); } for (int i = 0; i < B.length(); i++) { String key = B.charAt(i) + ""; Integer count = map.get(key); if (map.containsKey(key)) { map.put(key, --count); } if (count < 0) { return false; } } return true; }}
实质上利用的是哈希表的思想。只有大写字母,一共26个,遍历A的时候,往里面压,遍历B的时候,往外边弹,如果不够弹,则不包含。
0 0
- Lintcode—(3)比较字符串
- LintCode(容易)55.比较字符串
- LintCode(easy)比较字符串(正确版)
- Lintcode(2)-比较字符串
- LintCode比较字符串
- Lintcode 比较字符串
- lintcode-比较字符串-55
- LintCode 比较字符串
- Lintcode 比较字符串
- LintCode-比较字符串
- lintcode刷题--比较字符串
- LintCode 比较字符串
- Lintcode-比较字符串
- lintcode ----比较字符串
- LintCode之比较字符串
- lintCode 55:比较字符串
- LintCode : 比较字符串
- Lintcode 比较字符串
- Mongodb学习系列
- numpy广播机制
- jquery常用方法,<br/>替换等
- enote笔记语言(4)
- 【solr】——全文检索实现原理
- Lintcode—(3)比较字符串
- 正太分布的前世今生
- oracle 12c演示模式正确打开姿势
- HTTP协议详解
- 剪刀石头布
- Android 解决界面底部弹出dialog被虚拟按键遮挡一部分的问题
- js职责链模式
- VS 2015 + Qt 5.8 环境配置
- FileChannel 与 ByteBuffer 操作文件