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

来源:互联网 发布:java actionperformed 编辑:程序博客网 时间:2024/05/21 12:47

    • 需求
    • 解决思路
    • 一种写法的代码实现
    • 后记

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

上午看到一个面试题,是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);

后记:

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

阅读全文
1 0
原创粉丝点击