Keyboard Row问题及解法

来源:互联网 发布:忻州网络第一传媒 编辑:程序博客网 时间:2024/06/06 19:38

问题描述:

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.


American keyboard

示例:

Input: ["Hello", "Alaska", "Dad", "Peace"]Output: ["Alaska", "Dad"]
问题分析:

利用hashtable做好映射,比较每一个字符串的字符映射是否相等。

过程详见代码:

class Solution {public:    vector<string> findWords(vector<string>& words) {        vector<string> res;        vector<int> mapping(256,0);        char ch1[] = {'q','w','e','r','t','y','u','i','o','p','Q','W','E','R','T','Y','U','I','O','P'};        char ch2[] = {'a','s','d','f','g','h','j','k','l','A','S','D','F','G','H','J','K','L'};        char ch3[] = {'z','x','c','v','b','n','m','Z','X','C','V','B','N','M'};        for(int i = 0; i < 20;i++) mapping[ch1[i]] = 1;        for(int i = 0; i < 18;i++) mapping[ch2[i]] = 2;        for(int i = 0; i < 14;i++) mapping[ch3[i]] = 3;        for(int i = 0; i < words.size(); i++)        {        int t = mapping[words[i][0]];        int j = 1;        for(; j < words[i].length();j++)        {        if(mapping[words[i][j]] != t)        break;}if(j == words[i].length()) res.push_back(words[i]);}return res;    }};


0 0
原创粉丝点击