【Leetcode】527. Word Abbreviation

题目地址:

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是单词最长长度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值