LeetCode--500. 键盘行(C++描述)

我就是我 2022-08-28 06:40 257阅读 0赞

// Source : https://leetcode-cn.com/problems/keyboard-row/
// Date : 2021-10-12

题目描述:
在这里插入图片描述

题目分析:由于题目的提示说到word[i]的字符会包含大写和小写,因此我们在初始化键盘的字符的时候需要将大小写全部初始化,然后比较的时候,只要word的字符有大写或者小写的话,就将该计数器自增,然后比较完该字符的时候需要比较计数器和该字符的长度,如果相等的话,就将该字符加入结果数组。

代码:

  1. class Solution {
  2. public:
  3. vector<string> findWords(vector<string>& words)
  4. {
  5. vector<string> v;
  6. //将待查字符串的大小写都初始化
  7. string str1 = "qwertyuiop", str2 = "asdfghjkl", str3 = "zxcvbnm",
  8. str4="QWERTYUIOP", str5="ASDFGHJKL", str6="ZXCVBNM";
  9. //比较每一个单词
  10. for (int i = 0; i < words.size(); i++)
  11. {
  12. //count1、count2、count3分别用于计数第一、二、三行键盘元素的个数
  13. int count1 = 0, count2 = 0, count3 = 0;
  14. //比较该单词的每一个字符
  15. for (int j = 0; j < words[i].size(); j++)
  16. {
  17. //如果存在字符,就把字符串自增
  18. if (str1.find(words[i][j]) != -1||str4.find(words[i][j])!=-1)
  19. count1++;
  20. if (str2.find(words[i][j] )!=-1|| str5.find(words[i][j]) != -1)
  21. count2++;
  22. if (str3.find(words[i][j]) != -1 || str6.find(words[i][j]) != -1)
  23. count3++;
  24. }
  25. //如果存在相同字母的次数与word[i]的长度相同,则表示可由一行打出
  26. if (count1 == words[i].size() || count2 == words[i].size() || count3 == words[i].size())
  27. v.push_back(words[i]);
  28. }
  29. return v;
  30. }
  31. };

发表评论

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

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

相关阅读