LeetCode 500. Keyboard Row

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


Example 1:

Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]

如上所示,要求找出由键盘某一行中字母组合而成的单词。

解决方法:将各行字母分别存入Hash Table中,然后逐个判断数组中字符串即可。具体实现如下:

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

};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值