Skip to content

Commit 63f8056

Browse files
authored
Update 411.Minimum-Unique-Word-Abbreviation.cpp
1 parent 181cb74 commit 63f8056

File tree

1 file changed

+46
-48
lines changed

1 file changed

+46
-48
lines changed
Lines changed: 46 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,83 +1,81 @@
11
class Solution {
2+
int m;
23
public:
34
string minAbbreviation(string target, vector<string>& dictionary)
45
{
56
if (dictionary.size()==0)
6-
return to_string(target.size());
7-
8-
unordered_set<string>Set;
9-
int N = target.size();
7+
return to_string(target.size());
8+
this->m = target.size();
109

11-
for (auto str:dictionary)
10+
unordered_set<string>Set;
11+
for (auto word: dictionary)
1212
{
13-
if (str.size()==N)
14-
Set.insert(str);
15-
}
16-
17-
vector<pair<int,int>>masks;
18-
for (int i=0; i<(1<<N); i++)
19-
masks.push_back({len(i,N),i});
20-
sort(masks.begin(),masks.end());
13+
if (word.size()==m)
14+
Set.insert(word);
15+
}
16+
17+
vector<pair<int,int>>masks;
18+
for (int state = 0; state < (1<<m); state++)
19+
masks.push_back({len(state), state});
20+
sort(masks.begin(), masks.end());
2121

22-
for (int i=0; i<masks.size(); i++)
22+
for (auto x: masks)
2323
{
24-
int mask = masks[i].second;
25-
string a = abbr(target,mask);
24+
int mask = x.second;
25+
string abbr = getAbbr(target, mask);
2626
int flag = 1;
27-
28-
for (auto word:Set)
27+
28+
for (auto word: Set)
2929
{
30-
string b = abbr(word, mask);
31-
if (a==b)
30+
string s = getAbbr(word, mask);
31+
if (s==abbr)
3232
{
3333
flag = 0;
3434
break;
35-
}
36-
}
37-
if (flag == 1) return a;
35+
}
36+
}
37+
if (flag==1) return abbr;
3838
}
39-
return "";
39+
40+
return "";
4041
}
4142

42-
43-
int len(int mask, int N)
43+
string getAbbr(string& word, int mask)
4444
{
45-
int count = 0;
46-
for (int i=0; i<N; i++)
45+
string ret;
46+
for (int i=0; i<m; i++)
4747
{
48-
if (((mask>>i)&1)==1)
49-
count++;
48+
if ((mask>>i)&1)
49+
ret.push_back(word[i]);
5050
else
5151
{
52-
int j = i+1;
53-
while (j<N && ((mask>>j)&1)==0)
52+
int j = i;
53+
while (j<m && ((mask>>j)&1)==0)
5454
j++;
55-
count++;
55+
ret += to_string(j-i);
5656
i = j-1;
5757
}
58-
}
59-
return count;
58+
}
59+
return ret;
6060
}
6161

62-
string abbr(string A, int mask)
63-
{
64-
string result;
65-
int N = A.size();
66-
67-
for (int i=0; i<N; i++)
62+
int len(int mask)
63+
{
64+
int count = 0;
65+
for (int i=0; i<m; i++)
6866
{
69-
if (((mask>>i)&1)==1)
70-
result.push_back(A[i]);
67+
if ((mask>>i)&1)
68+
count++;
7169
else
7270
{
73-
int j = i+1;
74-
while (j<N && ((mask>>j)&1)==0)
71+
int j = i;
72+
while (j<m && ((mask>>j)&1)==0)
7573
j++;
76-
result += to_string(j-i);
74+
count += to_string(j-i).size();
7775
i = j-1;
7876
}
7977
}
80-
return result;
78+
return count;
79+
8180
}
82-
8381
};

0 commit comments

Comments
 (0)