Single-Row Keyboard
给一个字符串作为keyboard, 问另一个字符串中每个字符在这个keyboard上的距离差的和是多少.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Solution { public int calculateTime(String keyboard, String word) { Map<Character, Integer> map = new HashMap<>(); for(int i = 0; i < keyboard.length(); i++) { map.put(keyboard.charAt(i), i); } int sum = 0; int prev = 0; for(char c : word.toCharArray()){ if(prev != '1') { sum += Math.abs(map.get(c) - prev); } prev = map.get(c); } return sum; } } |