题目地址:
https://leetcode.com/problems/word-abbreviation/description/
给定若干小写字母的单词,每个单词长度都大于
1
1
1。要求按照下列规则产生所有单词的缩写:
1、每个单词的缩写格式是其前缀 + 省略的字符个数 + 最后一个字符,但要越短越好;
2、如果多个单词缩写相同,那么要选取最长的前缀,使得这些单词缩写变得不同;
3、如果缩写没有使得单词变得更短,那么不缩写。
要求返回的时候按原数组相同顺序排序。
参考https://mp.csdn.net/mp_blog/creation/success/109328602。代码如下:
class Solution {
public:
vector<string> wordsAbbreviation(vector<string>& ws) {
int n = ws.size();
vector<string> res(n);
unordered_map<string, int> mp;
int pre[n];
memset(pre, 0, sizeof pre);
auto abbr = [&](string& s, int i) {
if (i >= s.size() - 2) return s;
return s.substr(0, i) + to_string(s.size() - i - 1) + s.back();
};
for (int i = 0; i < n; i++) {
pre[i] = 1;
res[i] = abbr(ws[i], pre[i]);
mp[res[i]]++;
}
bool unique = false;
while (!unique) {
unique = true;
for (int i = 0; i < n; i++)
if (mp[res[i]] > 1) {
pre[i]++;
res[i] = abbr(ws[i], pre[i]);
mp[res[i]]++;
unique = false;
}
}
return res;
}
};
时空复杂度 O ( n l ) O(nl) O(nl), n n n是单词数量, l l l是单词最长长度。