[코테 풀이] Keyboard Row

시내·2024년 7월 29일

Q_500) Keyboard Row

출처 : https://leetcode.com/problems/keyboard-row/


class Solution {
    public String[] findWords(String[] words) {
        List<List<Character>> keyboard = makeKeyboard();
        String[] w = toLowerCases(words);
        List<Integer> list = new ArrayList<>();
        int location = -1;
        int soForthLocation = -1;
        for (int q = 0; q < w.length; q++) {
            loop1:
            for (int c = 0; c < keyboard.size(); c++) {
                if (keyboard.get(c).contains(w[q].charAt(0))) {
                    location = c;
                    for (int i = 1; i < w[q].length(); i++) {
                        for (int j = 0; j < keyboard.size(); j++) {
                            if (keyboard.get(j).contains(w[q].charAt(i))) {
                                soForthLocation = j;
                                if (soForthLocation != location) {
                                    break loop1;
                                }
                            }
                        }
                    }
                } else {
                    continue;
                }
                list.add(q);
            }
        }
        String[] answer = new String[list.size()];
        int index = 0;
        for (int i = 0; i < list.size(); i++) {
            answer[index++] = words[list.get(i)];
        }
        return answer;
    }
    
    public String[] toLowerCases(String[] words) {
        String[] toLowerCases = new String[words.length];
        int index = 0;
        for (int i = 0; i < words.length; i++) {
            String str = "";
            for (int j = 0; j < words[i].length(); j++) {
                if (Character.isUpperCase(words[i].charAt(j))) {
                    str += Character.toLowerCase(words[i].charAt(j));
                } else str += words[i].charAt(j);
            }
            toLowerCases[index++] = str;
        }
        return toLowerCases;
    }

    public List<List<Character>> makeKeyboard() {
        List<List<Character>> keyboard = new ArrayList<>();
        String first = "qwertyuiop", second = "asdfghjkl", third = "zxcvbnm";
        List<Character> eachRow = new ArrayList<>();
        for (int a = 0; a < first.length(); a++) {
            eachRow.add(first.charAt(a));
        }
        keyboard.add(new ArrayList<>(eachRow));
        eachRow.clear();
        for (int a = 0; a < second.length(); a++) {
            eachRow.add(second.charAt(a));
        }
        keyboard.add(new ArrayList<>(eachRow));
        eachRow.clear();
        for (int a = 0; a < third.length(); a++) {
            eachRow.add(third.charAt(a));
        }
        keyboard.add(new ArrayList<>(eachRow));
        return keyboard;
    }

}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글