500. Keyboard Row
来源:互联网 发布:如何修改考勤机数据 编辑:程序博客网 时间:2024/05/22 03:11
Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.
Example 1:
Input: ["Hello", "Alaska", "Dad", "Peace"]Output: ["Alaska", "Dad"]
Note:
- You may use one character in the keyboard more than once.
- You may assume the input string will only contain letters of alphabet.
题目要求:给定一个string数组,遍历数组中的string字符串,如果该字符串的每一个字母都在键盘上的同一行,则将其保留,否则删除该string。
我的思路是用一个数组来记录每一个字母在哪一行,从0-25分别记录a/A-z/Z这26个字母的所在行数,所以声明数组如下:
int mark[26] = {2,3,3,2,1,2,2,2,1,2,2,2,3,3,1,1,1,1,2,1,1,3,1,3,1,3};
当我遍历每个字符串中的每个字符时,我利用ASCii码来确定该字母在数组中的索引,然后将前后两个字母比较,判断是否在同一行:
for (int j = 1; j < words[i].size(); j++) { int index1 = (words[i][j-1] - 'a' >= 0) ? (words[i][j-1] - 'a') : (words[i][j-1] - 'A'); int index2 = (words[i][j] - 'a' >= 0) ? (words[i][j] - 'a') : (words[i][j] - 'A'); if (mark[index1] != mark[index2]) { isOneRow = false; break; } }
因为字符串中的字母有大小写之分,所以确定索引的时候要进行判断。
完整的代码如下:
class Solution {public: vector<string> findWords(vector<string>& words) { int mark[26] = {2,3,3,2,1,2,2,2,1,2,2,2,3,3,1,1,1,1,2,1,1,3,1,3,1,3}; vector<string> result; for (int i = 0; i < words.size(); i++) { bool isOneRow = true; for (int j = 1; j < words[i].size(); j++) { int index1 = (words[i][j-1] - 'a' >= 0) ? (words[i][j-1] - 'a') : (words[i][j-1] - 'A'); int index2 = (words[i][j] - 'a' >= 0) ? (words[i][j] - 'a') : (words[i][j] - 'A'); if (mark[index1] != mark[index2]) { isOneRow = false; break; } } if (isOneRow) result.push_back(words[i]); } return result; }};
阅读全文
0 0
- Leetcode-500. Keyboard Row
- 【Leetcode】500. Keyboard Row
- 500. Keyboard Row
- 500. Keyboard Row
- 【LeetCode】500. Keyboard Row
- 500. Keyboard Row
- LeetCode 500. Keyboard Row
- 500. Keyboard Row
- 500. Keyboard Row
- LeetCode 500. Keyboard Row
- 500. Keyboard Row
- 500. Keyboard Row (E)
- 500. Keyboard Row
- 500. Keyboard Row
- leetcode 500. Keyboard Row
- 500. Keyboard Row
- [LeetCode]500. Keyboard Row
- 500. Keyboard Row
- DOCBOX汇编命令
- CodeIgniter框架源码分析第一篇comnon.php
- git add . 提交时报错warning: LF will be replaced by CRLF in .gitignore.
- LUA 栈实现
- C++的结构体和位域
- 500. Keyboard Row
- 谈谈python的GIL、多线程、多进程
- 20171014w3school javascript课程学习
- js获取Android和iOS的版本
- 改善工作效率的3种方式
- 123
- QT自定义控件,以绘画板为例
- elasticsearch使用心得
- Struts2 安装