C++ solution with lambdas


  • 0
    D
    #include <algorithm>
    #include <iterator>
    #include <cctype>
    
    using namespace std;
    
    class Solution {
    private:
        map< char, int > keybord_map
        = {{'q', 1}, {'w', 1}, {'e', 1}, {'r', 1}, {'t', 1}, {'y', 1}, {'u', 1}, {'i', 1}, {'o', 1},
           {'p', 1}, {'a', 2}, {'s', 2}, {'d', 2}, {'f', 2}, {'g', 2}, {'h', 2}, {'j', 2}, {'k', 2},
           {'l', 2}, {'z', 3}, {'x', 3}, {'c', 3}, {'v', 3}, {'b', 3}, {'n', 3}, {'m', 3}};
    
    public:
        vector< string > findWords( vector< string >& words )
        {
            vector< string > result_words;
            auto all_char_on_same_line = [&]( string str ) {
               transform( str.begin( ), str.end( ), str.begin( ),
                          []( unsigned char c ) { return tolower( c ); } );
    
                int chosen_line = keybord_map[ str[ 0 ] ];
                for ( char c : str )
                {
                    if ( keybord_map[ c ] != chosen_line )
                    {
                        return false;
                    }
                }
                return true;
            };
        
            for ( string& str : words )
            {
                if ( all_char_on_same_line( str ) )
                {
                    result_words.push_back( str );
                }
            }
            return result_words;
        }
    };

Log in to reply
 

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