Keyboard Row


Submit solution

Points: 40 (partial)
Time limit: 1.0s
Memory limit: 256M

Authors:
Problem type
Allowed languages
Java 19, Java 8

題目說明

請參考同學們目前在使用的鍵盤,應該會看到由上而下有三橫排字母,分別為

["qwertyuiop"]
["asdfghjkl"]
["zxcvbnm"]

接著讓使用者先輸入單字數量,之後輸入對應數量的單詞,並且判斷單詞是否拼字都在一橫行內完成

dad便是都在第二橫行中,而像cat便沒有

最後輸出所有由單一橫行拼出的單詞

輸入

數量 單詞

輸出

在同一橫行拼出的單詞

測試資料 輸入

4 Hello Alaska Dad Peace

測試資料 輸出

[Alaska, Dad]
//輸出格式注意!!

測試資料 輸入

1 cat

測試資料 輸出

[]

Comments


  • 0
    scu09156146  commented on May 17, 2024, 2:13 p.m.

    題解

    import java.util.ArrayList;
    import java.util.Scanner;
    
    public class KBRow {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Scanner in = new Scanner(System.in);
            String[] a = { "qwertyuiop", "asdfghjkl", "zxcvbnm" }; // 鍵盤第1、2、3行
            int n = in.nextInt();
            ArrayList<String> s = new ArrayList<>();
    
            // 【迴圈1】:要檢查幾個單字
            for (int i = 0; i < n; i++) {
                String ss = in.next();
    
                // 【迴圈2】:要檢查幾行鍵盤
                for (int j = 0; j < 3; j++) {
                    // 根據單字的第一個字母,決定要"鎖定"檢查鍵盤第幾行
                    if (a[j].contains((String.valueOf(ss.charAt(0))).toLowerCase())) {
                        boolean f = true;
    
                        // 【迴圈3】:單字有幾個字母要檢查
                        for (int k = 1; k < ss.length(); k++) {
                            if (!a[j].contains((String.valueOf(ss.charAt(k))).toLowerCase())) {
                                f = false;
                                break; // 跳出【迴圈3】,根據f變數,決定是否把這個單字加進ArrayList
                            }
                        }
                        if (f)
                            s.add(ss);
                        else
                            break; // 跳出【迴圈2】,接下去檢查下一個單字
                    }
                }
            }
            in.close(); // 所有單字檢查完畢
    
            System.out.print(s); // 印出符合條件的單字清單。直接使用print()印出ArrayList的內容!
        }
    
    }