1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution { public int uniqueLetterString(String s) { int[] lastIndexMap = new int[26]; int[] curIndexMap = new int[26]; Arrays.fill(lastIndexMap, -1); Arrays.fill(curIndexMap, -1); char[] cs = s.toCharArray(); int ans = 0, length = cs.length; for (int i = 0; i < length; i++) { int index = cs[i] - 'A'; if (curIndexMap[index] > -1) { ans += (curIndexMap[index] - lastIndexMap[index]) * (i - curIndexMap[index]); } lastIndexMap[index] = curIndexMap[index]; curIndexMap[index] = i; } for (int i = 0; i < 26; i++) { if (curIndexMap[i] > -1) { ans += (curIndexMap[i] - lastIndexMap[i]) * (s.length() - curIndexMap[i]); } } return ans; } }
|