题解 | #手机键盘#
手机键盘
https://www.nowcoder.com/practice/20082c12f1ec43b29cd27c805cd476cd
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { // 按键次数 int[] keyCount = {1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,4,1,2,3,1,2,3,4}; // 字母位置 int[] keyLocation = {1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,6,7,7,7,8,8,8,8}; Scanner in = new Scanner(System.in); while (in.hasNext()) { String str = in.next(); int preIndex = 0; int total = 0; for (int i = 0; i < str.length(); i++) { char current = str.charAt(i);// 当前字符 int currentIndex = 26 - ('z' - current + 1);// 当前字符索引 if (i!=0) {// 第一次循环跳过前一个字符的运算 if(keyLocation[preIndex] == keyLocation[currentIndex]){ total += 2; } } total += keyCount[currentIndex]; preIndex = currentIndex; } System.out.println(total); } } }