【leetcode】893. Groups of Special-Equivalent Strings

Algorithm

【leetcode】893. Groups of Special-Equivalent Strings

https://leetcode.com/problems/groups-of-special-equivalent-strings/

1)problem

You are given an array A of strings.

Two strings S and T are special-equivalent if after any number of moves, S == T.

A move consists of choosing two indices i and j with i % 2 == j % 2, and swapping S[i] with S[j].

Now, a group of special-equivalent strings from A is a non-empty subset S of A such that any string not in S is not special-equivalent with any string in S.

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

Example 1:

Input: ["a","b","c","a","c","c"]
Output: 3
Explanation: 3 groups ["a","a"], ["b"], ["c","c","c"]

Example 2:

Input: ["aa","bb","ab","ba"]
Output: 4
Explanation: 4 groups ["aa"], ["bb"], ["ab"], ["ba"]

Example 3:

Input: ["abc","acb","bac","bca","cab","cba"]
Output: 3
Explanation: 3 groups ["abc","cba"], ["acb","bca"], ["bac","cab"]

Example 4:

Input: ["abcd","cdab","adcb","cbad"]
Output: 1
Explanation: 1 group ["abcd","cdab","adcb","cbad"]

Note:

  • 1 <= A.length <= 1000
  • 1 <= A[i].length <= 20
  • All A[i] have the same length.
  • All A[i] consist of only lowercase letters.

2)answer

统计奇数位和偶数位的个字符出现的次数,如果 S0 串和 S1 串统计的结果相同,则它们是 special-equivalent 的。

3)solution

  1. 将字符串拆分为两个子字符串,1个包含偶数索引字符,1个包含奇数字符串
  2. 对两个子字符串进行排序(这样做是因为如果可以将字符串与另一个字符串交换,那么在排序时它们将彼此相等,因为它们必须具有相同的字符)
  3. 将一对字符串插入集合中,这将跟踪唯一的“组”
  4. 重新调整集合的大小

符合上面两个条件的是一组。

参考:https://blog.csdn.net/g_r_c/article/details/82079678

unordered_set使用方法

.find() 返回一个迭代器。这个迭代器指向和参数哈希值匹配的元素,如果没有匹配的元素,会返回这个容器的结束迭代器。
.end() 返回指向容器末尾位置的迭代器
.insert() 插入元素 

视频:

https://www.youtube.com/watch?v=WJ4NtyrakT0&feature=youtu.be

图片示例:

C++实现代码:

#include "pch.h"
#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
#include <algorithm>
using std::vector;
using std::string;
using std::unordered_set;

class Solution {
public:
    int numSpecialEquivGroups(vector<string>& A) {
        unordered_set<string> st;
        for (int i = 0; i < A.size(); ++i) {
            string odd = "";
            string even = "";
            for (int j = 0; j < A[i].size(); ++j) {
                // 奇偶位的值
                if (j % 2 == 0)
                    odd += A[i][j];
                else
                    even += A[i][j];
            }
            // 排序奇偶位的值
            sort(odd.begin(), odd.end());
            sort(even.begin(), even.end());
            st.insert(odd + even);

        }
        return st.size();
    }
};
int main()
{
    Solution solution;
    vector<string> A1 = { "abcd", "cdab", "adcb", "cbad" };
    vector<string> A2 = { "abc", "acb", "bac", "bca", "cab", "cba" };
    int res1 = solution.numSpecialEquivGroups(A1);
    int res2 = solution.numSpecialEquivGroups(A2);
}

Python实现:

def numSpecialEquivGroups(self,A):
    s = set()
    for w in A:
        even = ''.join(sorted(w[0::2]))
        odd  = ''.join(sorted(w[1::2]))
        s.add(odd+even)
    return len(s)

原文地址:https://www.cnblogs.com/17bdw/p/10381327.html

时间: 2024-10-12 16:18:47

【leetcode】893. Groups of Special-Equivalent Strings的相关文章

【leetcode】Generate Parentheses

题目: 给定整数n,返回n对匹配的小括号字符串数组. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 分析: 这种问题的模式是:1)问题的解有多个 ,2)每个解都是由多个有效的 "步骤" 组成的,3)变更以有解的某个或某些"步骤"

【LeetCode】Implement strStr()

Implement strStr() Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 标准KMP算法.可参考下文. http://blog.csdn.net/yaochunnian/article/details/7059486 核心思想在于求出模式串前缀与后缀中重复部分,将重复信息保存在n

【LeetCode】Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 ->

【LeetCode】Pascal&#39;s Triangle

Pascal's Triangle Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 这题别想用通项公式做,n choose m里面的连乘必然溢出,老老实实逐层用定义做. class Solution { public: vector<vector<

【LeetCode】Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. 思路:第一遍正常复制链表,同时用哈希表保存链表中原始节点和新节点的对应关系,第二遍遍历链表的时候,再复制随机域. 这是一种典型的空间换时间的做法,n个节点,需要大小为O(n

【leetcode】Max Points on a Line (python)

给定一个点,除该点之外的其他所有点中,与该点的关系要么是共线,要么就是共点,也就是两点重合. 共线有三种情况:水平共线,垂直共线,倾斜的共线.合并下这三种情况就是斜率存在的共线和斜率不存在的共线. 那么我们的任务就是针对每个点,找出与其共线的这些情况中,共线最多的点的个数. 注意:最终的结果别忘了加上共点的个数. class Solution: def maxPoints(self, points ): if len( points ) <= 1: return len( points ) ma

【LeetCode】 Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6. More practice: If you have figu

【Leetcode】Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space cha

【Leetcode】Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ / 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] 思路:与[Leetcode]Path Sum 不同