Java Solution

  • 0

    We will create three counters, that will represent each row in the keyboard,then will iterate over the given array, and will check for th keyboard's row that the letter is belong.
    if the keyboard counter equals to the word length, we can know that it can be typed by one row.
    Java 8 code:
    package Q500.Keyborad_row;

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;

    //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.

    public class Row {

    public static void main(String[] args) {
    	Row r = new Row();
    	String[] str = { "Hello", "Alaska", "Dad", "Peace" };
    public String[] findWords(String[] words) {
    	/** Keyboard rows array **/
    	String[] keyboard = { "qwertyuiop", "asdfghjkl", "zxcvbnm" };
    	/** return list **/
    	List<String> list = new ArrayList<>();
    	/**Iterate over one word from the input array**/
    	for (int i = 0; i < words.length; i++) {
    		String strWord = words[i];
    	/**Counter for each keybord's row, once the row's counter equal to the word length we know that
    	 * the word can be typed using one row.
    		int keyRow0Counter = 0;
    		int keyRow1Counter = 0;
    		int keyRow2Counter = 0;
            /**Iterate over the characters of the word**/
    		for (int j = 0; j < strWord.length(); j++) {
    			char charWord = strWord.charAt(j);
    			if (Character.isUpperCase(charWord))
    				charWord = Character.toLowerCase(charWord);
    			if (keyboard[0].contains(Character.toString(charWord)))
    			else if (keyboard[1].contains(Character.toString(charWord)))
    			else if (keyboard[2].contains(Character.toString(charWord)))
    		if (keyRow0Counter == strWord.length() || keyRow1Counter == strWord.length()
    				|| keyRow2Counter == strWord.length())
    	return list.toArray(new String[list.size()]);



Log in to reply

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