C++ solution use array 0ms


  • 0
    Y

    use space for time

    vector<string> findWords(vector<string>& words) {
            vector<string> result;
            string str1 = "qwertyuiop",str2 = "asdfghjkl",str3 = "zxcvbnm";
            int a[26];   //a[26] stand for alphabet
            int i;
            while (i<str1.size() || i<str2.size() || i<str3.size())
            {
                if (i<str1.size())  a[str1[i]-'a'] = 1; //"qwertyuiop"  1
                if (i<str2.size())  a[str2[i]-'a'] = 2;//"asdfghjkl" 2
                if (i<str3.size())  a[str3[i]-'a'] = 3;//"zxcvbnm" 3
                ++i;
            }
    //a[] = { 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 };
    
            for (i=0;i<words.size();++i)
            {
                int j;
                for (j=0;j<words[i].size();++j)
                {
                   if (a[tolower(words[i][j])-'a'] != a[tolower(words[i][0])-'a']) 
                          break;
                }
                if (j==words[i].size())  
                {
                    result.push_back(words[i]);
                }
            }
            return result;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.