内容简介:称一个字符串中,互换第奇数位(或偶数位)形成的新单词与原单词为特殊相等。给定一个字符串数组
D46 893. Groups of Special-Equivalent Strings
题目链接
893. Groups of Special-Equivalent Strings
题目分析
称一个字符串中,互换第奇数位(或偶数位)形成的新单词与原单词为特殊相等。
给定一个字符串数组 A
,计算该数组中有多少个独立的特殊相等词。
例如,单词 abcd
和 cbad
为特殊相等词。也与 adcb
和 cdab
特殊相等。
思路
先把字符串分割成数组,把第偶数个字符和第奇数个字符分别存放。
再对偶数字符数组和奇数字符数组进行排序。
接下来用分隔符拼接这两个数组。使得对任何一个特殊相等的词都有同一个值。把拼接后的字符串作为键存入数组中。(作为值存进去的话需要去重)
计算数组中的元素个数即可。
最终代码
<?php
class Solution {
function numSpecialEquivGroups($A) {
$words = [];
foreach($A as $b){
$odd = $even = [];
$chars = str_split($b);
foreach($chars as $key=>$char){
if($key%2==0){
$odd[] = $char;
}
else{
$even[] = $char;
}
}
sort($odd);
sort($even);
$words[implode('',$odd).'/'.implode('',$even)] = true;
}
return count($words);
}
}
若觉得本文章对你有用,欢迎用[爱发电](https://afdian.net/@skys215)资助。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Agile Web Application Development with Yii 1.1 and PHP5
Jeffrey Winesett / Packt Publishing / 2010-08-27
In order to understand the framework in the context of a real-world application, we need to build something that will more closely resemble the types of applications web developers actually have to bu......一起来看看 《Agile Web Application Development with Yii 1.1 and PHP5》 这本书的介绍吧!