您的位置:首页 > 教育 > 培训 > leetcode 893. Groups of Special-Equivalent Strings

leetcode 893. Groups of Special-Equivalent Strings

2025/2/27 9:36:26 来源:https://blog.csdn.net/wuyexiaobailong/article/details/141530841  浏览:    关键词:leetcode 893. Groups of Special-Equivalent Strings

原题链接

You are given an array of strings of the same length words.

In one move, you can swap any two even indexed characters or any two odd indexed characters of a string words[i].

Two strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j].

  • For example, words[i] = "zzxy" and words[j] = "xyzz" are special-equivalent because we may make the moves "zzxy" -> "xzzy" -> "xyzz".

group of special-equivalent strings from words is a non-empty subset of words such that:

  • Every pair of strings in the group are special equivalent, and
  • The group is the largest size possible (i.e., there is not a string words[i] not in the group such that words[i] is special-equivalent to every string in the group).

Return the number of groups of special-equivalent strings from words.

按奇偶位置顺序重新排列字符串,然后统计有多少个不重复的字符串

class Solution {
public:int numSpecialEquivGroups(vector<string>& words) {unordered_map<string,bool> mp;for (int i = 0; i< words.size(); i ++) {int tmp =  (words[i].size()-1)>>1;rerank(words[i], 0, 0, tmp );if ((words[i].size()&1) != 0) tmp --;rerank(words[i], 1, 0 , tmp);mp[words[i]] = true;}return mp.size();}void rerank(string & w, int p, int be, int en) {if (be >= en) return;char tmp = w[be*2 + p];int oldbe = be, olden = en;while(be < en) {while (be < en && w[be*2 + p] <= tmp) be++;while (oldbe < en && w[en*2 + p] >= tmp) en--;if(be < en) swap(w[be*2 + p], w[en*2 + p]);}swap(w[oldbe*2 + p], w[en*2 + p]);if (oldbe  < en-1) rerank(w, p, oldbe,en-1);if (en+1 < olden) rerank(w, p, en+1, olden);}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com