LeetCode-Python-893. Groups of Special-Equivalent Strings

  • 题目理解

  • 编程方法

一.题目理解

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

题目中提到的转换(move)指的是交换n次偶数次位置或者奇数次位置的字符。如果字符串A可以通过move转换为字符串B,即认为两者是special-equivalent strings。

题目中提到字符串都由小写字母组成,且字符串数组中字符串的长度是一致的。

要求寻找特殊等价字符串的个数。

字符串中一共包括26个小写字母,即可创建一个序列(KEY)统计个数。序列可以由偶数次位置与奇数次位置的顺序组成。

二.编程方法

Python 中字典是一种可存储任何类型对象的容器,值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

sameWord={}
for i in A:
    if len(i)>=2:
       key=(tuple(sorted(i[1::2])),tuple(sorted(i[0::2]))) //创建序列key
    else:
        key=i //字符串为单字母时自身满足等价
    sameWord[key]=sameWord.get(key,0)+1 //计数
print(len(sameWord))

上述即为利用字典数据结构来统计个数,Key为等价字符串,值为个数。

题目要求只统计个数,不要具体等价字符串的值。由此可以利用另一个数据结构Set,是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素。所以直接将各自排序好的偶奇次拼接为字符串放入set中,最后输出set的长度即为等价字符串的个数。

 

sameWord2=set()
for i in A:

    sameWord2.add("".join(sorted(i[0::2]))+"".join(sorted(i[1::2])))
    print(len(sameWord2))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值