leetcode-500. 键盘行


题目

500. 键盘行

解法

很简单,首先维护一个字符位置的映射关系,判断每个字符的每一位是否在一行

哈希表

class Solution {
    const LINE_CHARS = [
        '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,
    ];
    
    /**
     * @param String[] $words
     * @return String[]
     */
    function findWords($words) {
        $ret = [];
        foreach ($words as $word) {
            $lastLine = null;
            for ($i = 0; $i < strlen($word); $i++) {
                $curChar = strtolower($word[$i]);
                $curCharLine = self::LINE_CHARS[$curChar];
                if (!is_null($lastLine) && $curCharLine != $lastLine) {
                    continue 2;
                }
                
                $lastLine = $curCharLine;
            }
            
            $ret[] = $word;
        }
        
        return $ret;
    }
}

参考