给定一个字符串 S,我们的任务是检查该字符串是否可以仅使用 QWERTY 键盘的同一行输入。
示例:
> 输入: S = "Dad"
> 输出: Yes
> 解释:
> 字符 "D" 和 "a" 位于 QWERTY 键盘的同一行,即第二行。
>
>
>
>
>
> 输入: S = "Mom"
> 输出: No
> 解释:
> 字符 "M" 和 "o" 不在 QWERTY 键盘的同一行。
方法: 我们的核心思路是将 QWERTY 键盘同一行的字符存储在不同的 哈希映射 中,以便检查字符串中的所有字符是否都来自同一行。
下面是该方法的实现:
C++
CODEBLOCK_71a662f9
Java
“
// Java program to check whether
// the string can be printed
// using same row of qwerty keypad
import java.util.*;
class GFG{
// Function to find the row of the
// character in the qwerty keypad
static int checkQwertyRow(char x)
{
// Sets to include the characters
// from the same row of the qwerty keypad
Character[] first_row1 = { ‘1‘, ‘2‘, ‘3‘, ‘4‘,
‘5‘, ‘6‘, ‘7‘, ‘8‘,
‘9‘, ‘0‘, ‘-‘, ‘=‘ };
Set first_row = new HashSet(
Arrays.asList(first_row1));
Character[] second_row1 = { ‘Q‘, ‘W‘, ‘E‘, ‘R‘, ‘T‘,
‘Y‘, ‘U‘, ‘I‘, ‘O‘, ‘P‘,
‘[‘, ‘]‘, ‘q‘, ‘w‘, ‘e‘,
‘r‘, ‘t‘, ‘y‘, ‘u‘, ‘i‘,
‘o‘, ‘p‘ };
Set second_row = new HashSet(
Arrays.asList(second_row1));
Character[] third_row1 = { ‘A‘, ‘S‘, ‘D‘, ‘F‘, ‘G‘,
‘H‘, ‘J‘, ‘K‘, ‘L‘, ‘;‘,
‘:‘, ‘a‘, ‘s‘, ‘d‘, ‘f‘,
‘g‘, ‘h‘, ‘j‘, ‘k‘, ‘l‘ };
Set third_row = new HashSet(
Arrays.asList(third_row1));
Character[] fourth_row1 = { ‘Z‘, ‘X‘, ‘C‘, ‘V‘, ‘B‘,
‘N‘, ‘M‘, ‘,‘, ‘.‘,
‘/‘, ‘z‘, ‘x‘, ‘c‘, ‘v‘,
‘b‘, ‘n‘, ‘m‘ };
Set fourth_row = new HashSet(
Arrays.asList(fourth_row1));
// Condition to check the row of the
// current character of the string
if (first_row.contains(x))
{
return 1;
}
else if (second_row.contains(x))
{
return 2;
}
else if (third_row.contains(x))
{
return 3;
}
else if (fourth_row.contains(x))
{
return 4;
}
return 0;
}
// Function to check the characters are
// from the same row of the qwerty keypad
static boolean checkValidity(String str)
{
char x = str.charAt(0);
int row = checkQwertyRow(x);
for(int i = 0; i < str.length(); i++)
{
x = str.charAt(i);
if (row != checkQwertyRow(x))
{
return false;
}
}
return true;
}
// Driver cod