题目地址:
https://www.lintcode.com/problem/distinguish-username/description
给定一个字符串数组 A A A,要求返回一个同长的数组 B B B,使得 B [ i ] B[i] B[i]是 A [ i ] A[i] A[i]拼接上其前面的子数组里其出现的次数。次数是 0 0 0则省略。
思路是哈希表,记录每个字符串出现次数。代码如下:
import java.util.HashMap;
import java.util.Map;
public class Solution {
/**
* @param names: a string array
* @return: the string array
*/
public String[] DistinguishUsername(String[] names) {
// Write your code here
String[] res = new String[names.length];
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < names.length; i++) {
map.put(names[i], map.getOrDefault(names[i], 0) + 1);
int val = map.get(names[i]);
res[i] = val > 1 ? names[i] + (val - 1) : names[i];
}
return res;
}
}
时间复杂度 O ( n l ) O(nl) O(nl), n n n是数组长度, l l l是最长字符串长度。