根据php中的特殊字符集对数组进行排序

时间:2019-01-06 05:55:38

标签: php algorithm sorting

我有这个问题: 考虑小写的n个单词的数组。实现一个功能以查找具有相同唯一字符集的所有单词。具有相同字符集的所有单词都按照它们在数组中出现的顺序一起打印在一行中。

如果输入是: 6 学生 学生们 狗 学生们 神 猫

预期输出应为: 学生,学生,学生, 狗,神, 猫

我能够在python中提出一个解决方案,但是我需要将该解决方案转换为PHP,您的建议将对我有很大帮助。

python中的解决方案是这样:

# Function to group all strings with same characters 
from collections import Counter 

def groupStrings(input): 
    # traverse all strings one by one 
    # dict is an empty dictionary 
    dict={} 

    for word in input: 
        # sort the current string and take it's 
        # sorted value as key 
        # sorted return list of sorted characters 
        # we need to join them to get key as string 
        # Counter() method returns dictionary with frequency of 
        # each character as value 
        wordDict=Counter(word) 

        # now get list of keys 
        key = wordDict.keys() 

        # now sort these keys 
        key = sorted(key) 

        # join these characters to produce key string 
        key = ''.join(key) 

        # now check if this key already exist in 
        # dictionary or not 
        # if exist then simply append current word 
        # in mapped list on key 
        # otherwise first assign empty list to key and 
        # then append current word in it 
        if key in dict.keys(): 
            dict[key].append(word) 
        else: 
            dict[key]=[] 
            dict[key].append(word) 

        # now traverse complete dictionary and print 
        # list of mapped strings in each key seprated by , 
    for (key,value) in dict.iteritems(): 
        print ','.join(dict[key]) 

# Driver program 
if __name__ == "__main__": 
    input=['may','student','students','dog','studentssess','god','cat','act','tab','bat','flow','wolf','lambs','amy','yam','balms','looped','poodle'] 
    groupStrings(input) 

1 个答案:

答案 0 :(得分:1)

因为PHP可以使用不同的函数名称或语法完全相同地完成collections.Counter以外的所有任务。首先,您需要使用count_chars($word, 1)代替collections.Counter,然后使用chr将返回的数组映射到字符。

此后,仅用PHP等效语言替换了Python语法。

示例:https://3v4l.org/V6HBg

function groupStrings($input)
{
    $words = $dict = [];
    foreach ($input as $word) {
       //emulate python collections.Counter() using count_chars()
       $wordDict = \count_chars($word, 1);

       //get the character value returned from keys of count_chars()
       $key = \array_map(function($v) {
           return \chr($v);
       }, \array_keys($wordDict));

       //sort alphabetically A-Z (ignores case)
       \natcasesort($key);

       //create an associative index from the key
       $key = \implode('', $key);

       if (!\array_key_exists($key, $dict)) {
           $dict[$key] = [];
       }
       $dict[$key][] = $word;
    }

    foreach ($dict as $key => $word) {
        $words[] = \implode(',', $word);
    }

    return \implode(',', $words);
}

$input = ['student', 'students', 'dog', 'studentssess', 'god', 'cat'];
echo groupStrings($input);

结果:

student,students,studentssess,dog,god,cat

完整结果:

may,amy,yam,student,students,studentssess,dog,god,cat,act,tab,bat,flow,wolf,lambs,balms,looped,poodle

简化版本https://3v4l.org/SuAI5

由于您只对每个单词中的字符感兴趣,而对它们的出现频率不感兴趣,因此我们可以取代将键转换为字符的昂贵的count_charsarray_map转换,并使用{{1 }}放在array_unique上。

str_split