leetcode - 500. Keyboard Row (map)

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.


leetcode - 500. Keyboard Row (map)_第1张图片


Example 1:

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

Note:

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet
my solution:
大致思路:
如果一个单词里面所有字符都在键盘的同一行,则保留,否则删除。

我先对键盘的所有字符建一个字典<字符,行号>,下面的就方便查找了(里面红黑树,字符有排序,查找快)。初始化字典的工作只用做一次,一次初始化化,多次调用。

class Solution {
public:
	static vector findWords(vector& words) {
		if (0 ==init_flag)
		{
		    //!初始化的工作其实可以放在开始findWords之前
		    init_dictionary ();
		}
        
               int pre_flag = -1;
        
               for (int i = 0; i < words.size(); )
               {
                     for (int j = 0; j < words[i].size(); ++ j)
                     {
                         char ch = words[i][j] >= 'a' ? words[i][j] - 'a' + 'A' : words[i][j];
                
                         if (pre_flag == -1)
                         {
                             pre_flag = find_dictionary(ch);
                             continue;
                         }
                         else if (pre_flag == find_dictionary(ch))
                         {
                            continue;
                         }
                         else //pre_flag != find_dictionary(ch)
                         {
                             words.erase(words.begin()+i);
                             pre_flag = -1;
                             break;
                         }
                     }//for
            
                     if (-1 != pre_flag)
                     {
                        ++i;
                        pre_flag = -1;
                     }
            
                }//for
		return words;
	}
	
	static void init_dictionary ()
	{
	    string a = "QWERTYUIOP";
		string b = "ASDFGHJKL";
		string c = "ZXCVBNM";
		
		for (int i = 0; i < a.size(); ++i)
		{
		    dict[a[i]] = 0;
		}
		for (int i = 0; i < b.size(); ++i)
		{
		    dict[b[i]] = 1;
		}
		for (int i = 0; i < c.size(); ++i)
		{
		    dict[c[i]] = 2;
		}
		
		init_flag = 1;
	}
	
	static int find_dictionary (char ch)
	{
	    //!这里因为输入都是正常,所以没有考虑迭代器是end,实际要考虑的
	    return (dict.find(ch))->second;
	}
	
	static map dict;
	static int init_flag;
};

int Solution::init_flag = 0;
map Solution::dict;












你可能感兴趣的:(leetcode - 500. Keyboard Row (map))