dongtuo0828 2016-07-03 05:16
浏览 23

在具有最大特定字符数的句子中查找单词

I am new to PHP Development and finally with the help of SO I am able to write a program for finding word in a sentence with maximum specific character count.

Below is what I have tried:

<?php
// Program to find the word in a sentence with maximum specific character count
// Example: "O Romeo, Romeo, wherefore art thou Romeo?”
// Solution: wherefore 
// Explanation: Because "e" came three times
$content = file_get_contents($argv[1]); // Reading content of file
$max = 0;
$arr = explode(" ", $content); // entire array of strings with file contents
for($x =0; $x<count($arr); $x++) // looping through entire array 
{
$array[$x] = str_split($arr[$x]); // converting each of the string into array
}
for($x = 0; $x < count($arr); $x++)
{
    $count = array_count_values($array[$x]);
    $curr_max = max($count);
    if($curr_max > $max)
    {
        $max = $curr_max;
        $word = $arr[$x];
    }
}
echo $word;
?>

Question: Since I am new to PHP development I don't know the optimization techniques. Is there anyway I can optimize this code? Also, Can I use regex to optimize this code further? Kindly guide.

  • 写回答

1条回答 默认 最新

  • douzhaiya3968 2016-07-03 06:27
    关注

    I love coding this type of mini-challenges in the minimum lines of code :D. So here is my solution:

    function wordsWithMaxCharFrequency($sentence) {
    
        $words = preg_split('/\s+/', $sentence);
    
        $maxCharsFrequency = array_map (function($word) {
            return max(count_chars(strtolower($word)));
        }, $words);
    
        return array_map(function($index) use($words) {
            return $words[$index];
        }, array_keys($maxCharsFrequency, max($maxCharsFrequency)));
    }
    
    print_r(wordsWithMaxCharFrequency("eeee yyyy"));
    //Output: Array ( [0] => eeee [1] => yyyy )
    
    print_r(wordsWithMaxCharFrequency("xx llll x"));
    //Output: Array ( [0] => llll )
    

    Update1:

    If you want to get only A-Za-z words use the following code:

    $matches = [];
    //a word is either followed by a space or end of input
    preg_match_all('/([a-z]+)(?=\s|$)/i', $sentence, $matches); 
    $words = $matches[1];
    

    Just a contribution that could inspire you :D!

    Good Luck.

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料