目录
扫描二维码关注公众号,回复:
14306494 查看本文章
![](/qrcode.jpg)
一、题目一 500. 键盘行
1、题目描述
给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。
美式键盘 中:
第一行由字符 "qwertyuiop" 组成。
第二行由字符 "asdfghjkl" 组成。
第三行由字符 "zxcvbnm" 组成。
示例 1:
输入:words = ["Hello","Alaska","Dad","Peace"] 输出:["Alaska","Dad"]
示例 2:
输入:words = ["omk"] 输出:[]
示例3:
输入:words = ["adsdf","sfd"] 输出:["adsdf","sfd"]
2、基础框架
Java 版本给出的基础框架代码如下:
class Solution {
public int maximumDifference(int[] nums) {
}
提示:
n == nums.length
2 <= n <= 1000
1 <= nums[i] <= 109
3、原题链接
LeetCode 500. 键盘行
二、解题报告
1、思路分析
见代码详解注释
2、代码详解
class Solution {
public String[] findWords(String[] words) {
List<String> list = new ArrayList<String>();
String rowIdx = "12210111011122000010020202";
for (String word : words) {
boolean isValid = true;
char idx = rowIdx.charAt(Character.toLowerCase(word.charAt(0)) - 'a');
for (int i = 1; i < word.length(); ++i) {
if (rowIdx.charAt(Character.toLowerCase(word.charAt(i)) - 'a') != idx) {
isValid = false;
break;
}
}
if (isValid) {
list.add(word);
}
}
String[] ans = new String[list.size()];
for (int i = 0; i < list.size(); ++i) {
ans[i] = list.get(i);
}
return ans;
}
}
二、题目二 1160. 拼写单词
1、题目描述
给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
注意:每次拼写(指拼写词汇表中的一个单词)时,chars 中的每个字母都只能用一次。
返回词汇表 words 中你掌握的所有单词的 长度之和。
示例 1:
输入:words = ["cat","bt","hat","tree"], chars = "atach"
输出:6
解释:
可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。
示例 2:
输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
输出:10
解释:
可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。
2、基础框架
Java 版本给出的基础框架代码如下:
class Solution {
public int countCharacters(String[] words, String chars) {
}
提示:
- 1 <= words.length <= 1000
- 1 <= words[i].length, chars.length <= 100
- 所有字符串中都仅包含小写英文字母
3、原题链接
LeetCode 1160. 拼写单词
二、解题报告
1、思路分析
见代码详解注释
2、代码详解
class Solution {
public int countCharacters(String[] words, String chars) {
int[] hash = new int[26];
for(char ch : chars.toCharArray()){
hash[ch - 'a'] += 1;
}
int[] map = new int[26];
int len = 0;
for(String word : words){
Arrays.fill(map, 0);
boolean flag = true;
for(char ch : word.toCharArray()){
map[ch - 'a']++;
if(map[ch - 'a'] > hash[ch - 'a']) flag = false;
}
len += flag ? word.length() : 0;
}
return len;
}
}