LeetCode(Map)1832. Check if the Sentence Is Pangram

曾经终败给现在 2023-09-24 17:09 41阅读 0赞

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:

  1. class Solution {
  2. public boolean checkIfPangram(String sentence) {
  3. if (sentence.length() < 26) {
  4. //1.如果长度小于26,直接返回false
  5. return false;
  6. }
  7. String alphas = "abcdefghijklmnopqrstuvwxyz";//2.定义String alphas为26个字母
  8. for (int i = 0; i < alphas.length(); i++) {
  9. //3.遍历循环,如果sentence.indexOf(alphas的char元素),如果等于-1,不存在,返回false;
  10. if (sentence.indexOf(alphas.charAt(i)) == -1) {
  11. return false;
  12. }
  13. }
  14. return true;//4.alphas的char元素遍历一遍,如果sentence全部有alphas的char元素,返回true;
  15. }
  16. }

代码2:

  1. class Solution {
  2. public boolean checkIfPangram(String sentence) {
  3. int[] count = new int[26];// 1.创建计数数组以计算每个字符。
  4. for(int i = 0; i<sentence.length(); i++)
  5. count[sentence.charAt(i) - 'a']++;//2.for循环遍历,sentence的char元素-'a',所在在位置
  6. for(int i : count)//3.在count数组的索引,如果小于1,没有元素,则为false
  7. if(i < 1) return false;
  8. return true;//4.满足条件返回true
  9. }
  10. }

代码3:

  1. class Solution {
  2. public boolean checkIfPangram(String sentence) {
  3. Set set = new HashSet<>();//1.利用set内没有重复元素
  4. for(char c : sentence.toCharArray()) set.add(c);//2.将sentence存入set,如果长度等于26为true,否则为false
  5. return set.size() == 26;
  6. }
  7. }

发表评论

表情:
评论列表 (有 0 条评论,41人围观)

还没有评论,来说两句吧...

相关阅读