按照单词的字母是否相同对字符串数组进行分组

好久不动手写代码了,真得有些生疏了。正所谓:曲不离口,拳不离手;勤行果然还是要常练习的。

上午看到一个面试题,是java版的,然后觉得给学生拿来做测试题不错,所以尝试写了一下,但真去做得时候,发现并不如相像那样简单。

需求:

给了一个数组(如: [“cars”, “thing”, “scar”, “dog”, “god”, “arcs”, “the”]),需要把由颠倒字母顺序组成的单词放到同一个数组(生成后的结果:[[“cars”, “scar”, “arcs”], [“thing”], [“dog”, “god”], [“the”]])

解决思路:

两重遍历,第一遍过按照给定数组过滤,第二重,把当前单词以外没有做过比较的单词与其进行比较

一种写法的代码实现:

<?php

$tool = ["cars", "thing", "scar", "dog", "god", "arcs", "the"];  // 用于遍历循环

$words = ["cars", "thing", "scar", "dog", "god", "arcs", "the"];  // 用于比较、排除的数组

$res =  array( );  // 用于存放结果


// 先遍历整个数组
foreach ($tool as $pos => $word) {

    $temp =  array();

    $wordArr = str_split($word);

    if (in_array($word, $words)) {

        // 以下if判断从比较数组中清除当前参与比较的单词
        $tempKey = array_search($word,$words);  
        if(isset($tempKey)){  
            unset($words[$tempKey]);  
        }

        $temp[] = $word; // 把当前单词加入临时数组;
    }else{
        continue; // 跳过已比较过的单词
    }

    // 以下循环将当前单词与未参与比较过的单词进行比较
    foreach ($tool as $comparingPos => $comparingWord) {

        if (in_array($comparingWord, $words)) {

            $comparingArr = str_split($comparingWord);    
            $intersect = array_intersect($comparingArr, $wordArr);

            if (count($wordArr)== count($intersect)) {
                $temp[] = $comparingWord; // 把当前单词加入临时数组;

                $tempKey = array_search($comparingWord,$words);  
                if(isset($tempKey)){  
                    unset($words[$tempKey]);  
                }
            }

        }else{
            continue;// 跳过已比较过的单词
        }
    }

    // 将比较结果放入数组
    if (!!$temp) {
        $res[] =$temp; 
    }
}

var_dump($res);

后记:

为啥要多余地写两个数组?因为循环计数器的问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值