LeetCode(Map)1832. Check if the Sentence Is Pangram
1.问题
A pangram is a sentence where every letter of the English alphabet appears at least once.
Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.
Example 1:
Input: sentence = “thequickbrownfoxjumpsoverthelazydog”
Output: true
Explanation: sentence contains at least one of every letter of the English alphabet.
Example 2:
Input: sentence = “leetcode”
Output: false
Constraints:
- 1 <= sentence.length <= 1000
- sentence consists of lowercase English letters.
2. 解题思路
方法1:
1.如果长度小于26,直接返回false
2.定义String alphas为26个字母
3.遍历循环,如果sentence.indexOf(alphas的char元素),如果等于-1,不存在,返回false;
4.alphas的char元素遍历一遍,如果sentence全部有alphas的char元素,返回true;
方法2:
1.创建计数数组以计算每个字符。
2.for循环遍历,sentence的char元素-‘a’,所在在位置
3.在count数组的索引,如果小于1,没有元素,则为false
4.满足条件返回true
方法3:
1.新建setmap,利用set内没有重复元素
2.将sentence存入set,如果长度等于26为true,否则为false
3. 代码
代码1:
class Solution {
public boolean checkIfPangram(String sentence) {
if (sentence.length() < 26) {
//1.如果长度小于26,直接返回false
return false;
}
String alphas = "abcdefghijklmnopqrstuvwxyz";//2.定义String alphas为26个字母
for (int i = 0; i < alphas.length(); i++) {
//3.遍历循环,如果sentence.indexOf(alphas的char元素),如果等于-1,不存在,返回false;
if (sentence.indexOf(alphas.charAt(i)) == -1) {
return false;
}
}
return true;//4.alphas的char元素遍历一遍,如果sentence全部有alphas的char元素,返回true;
}
}
代码2:
class Solution {
public boolean checkIfPangram(String sentence) {
int[] count = new int[26];// 1.创建计数数组以计算每个字符。
for(int i = 0; i<sentence.length(); i++)
count[sentence.charAt(i) - 'a']++;//2.for循环遍历,sentence的char元素-'a',所在在位置
for(int i : count)//3.在count数组的索引,如果小于1,没有元素,则为false
if(i < 1) return false;
return true;//4.满足条件返回true
}
}
代码3:
class Solution {
public boolean checkIfPangram(String sentence) {
Set set = new HashSet<>();//1.利用set内没有重复元素
for(char c : sentence.toCharArray()) set.add(c);//2.将sentence存入set,如果长度等于26为true,否则为false
return set.size() == 26;
}
}
还没有评论,来说两句吧...