【问题标题】:Finding the highest scoring word in a string, based on value of letter?根据字母的值找到字符串中得分最高的单词?
【发布时间】:2020-10-15 18:58:43
【问题描述】:

给定一串单词,我需要找到得分最高的单词。单词的每个字母都根据其在字母表中的位置来得分:a = 1、b = 2、c = 3 等。我需要将得分最高的单词作为字符串返回。

所以在字符串'man i need a taxi up to ubud' 中,正确的返回字符串应该是taxi,因为它有像t 和x 这样的高值字母。

我的困惑在于如何为每个单词中的每个字母分配一个值。我知道要分解输入字符串,然后对其进行 foreach 以分解单词,但是如何根据字母表中的顺序增加值?我很困惑。

function high($x) {
    $alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", 
                "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", 
                "u", "v", "w", "x", "y", "z"];
    $nA = array_flip($alphabet);

    $words = explode(" ", $x);
    foreach($words as $w) {
      explode("", $w);
    }
    return "";
}

【问题讨论】:

  • 为什么不拆分你的算法?一部分是“按单词拆分”,另一部分是“按单词生成分数”。那么,你有什么努力让它发挥作用?你被困在哪里了?
  • 我的问题在于将两者连接起来。这应该在一个函数内,我想不出如何连接拆分和生成分数。
  • 出于好奇:为什么需要一个函数?让它成为两个,以分离关注点。如果您愿意,可以稍后合并,但在开发过程中将其分开可能会有所帮助

标签: php


【解决方案1】:

正如您所说,您需要遍历每个单词 - 并为每个单词确定其分数。然后你需要保存那个单词的分数,以及单词本身,或者那个单词的位置。如果您计算的下一个分数比您保存的分数更高,则覆盖 - 否则,继续下一次迭代。最后,返回值。

使用strtolower() 确保单词是小写的,否则像A man with a XRAY 这样的字符串将找不到XRAY 作为得分最高的单词。

function high($input) {
    // Initialize: Convert the string to lowercase, and generate an array of the alphabet
    $input = strtolower($input);
    $alphabet = range('a', 'z');
    $values = array_flip($alphabet);

    // Split the words into an array, and declare initial scores
    $words = explode(" ", $input);
    $highestScore = null;
    $highestIndex = null;
    
    // Iterate over each word
    foreach($words as $k=>$w) {
        // Calculate the score of the current word
        // The score is the position of the flipped alphabet array, or 0 if its not in the lsit
        $score = array_sum(array_map(function($v) use ($values) {
            return $values[$v] ?? 0;
        }, str_split($w)));

        // If the current score is higher than the previous highest, overwrite it
        if ($highestScore < $score) {
            $highestScore = $score;
            $highestIndex = $k;
        }
    }

    // Return the word at the index where the score was the highest
    // If there were no scores (if $input is empty), return a default message
    return $words[$highestIndex] ?? 'N/A - No words found';
}

array_map() 函数将返回包含该单词(每个字母)的所有单独值的数组,因此我们使用 array_sum() 来获取数组的完整总和。

由于我们使用return $values[$v] ?? 0; 并且仅从a-z 创建值,因此任何其他字符的得分均为0。由于字符串转换为小写,这意味着它将处理a 和A相同的分数为 1。!?# 等特殊字符的分数为 0。

【讨论】:

    【解决方案2】:

    由于您实际上并不关心分数,更多的是具有最高字符的单词,您可以使用ord() 来计算 ascii 值。这具有升序排列的字母表,因此给出了更高的值 - 但它仍然基于位置。

    这会拆分单词,然后为每个单词添加 ascii 值并跟踪最高...

    function high($x) {
        // Split sentence into words (lower cased)
        $words = explode(" ", strtolower($x));
        $max = 0;
        $maxWord = '';
        foreach($words as $w) {
            // Keep track of 'value' of word
            $value = 0;
            // For each letter of the word ($i)...
            for ( $i = 0, $len = strlen($w); $i < $len; $i++ )  {
                // $w[$i]  is the letter we are dealing with (treat a string as an array)
                // Take the ascii value of this character and adjust it by 'a'
                $value += (ord($w[$i]) -ord('a'));
            }
            // Check if the new highest value
            if ( $value > $max )    {
                $max = $value;
                $maxWord = $w;
            }
        }
        return $maxWord;
    }
    

    【讨论】:

    • 使用ord()函数相当聪明,没想到。
    • 非常好的解决方案,但似乎不起作用? “断言两个字符串相等时失败。预期:'volcano' 实际:'climbing'” 也许这是一个错误?我很确定火山的价值更高。
    • "'我们什么时候爬上火山"
    • 我已更新循环并将其更改为(ord($w[$i]) -ord('a'));。
    • 你能试着解释一下吗?我现在马上就觉得很愚蠢:(
    猜你喜欢
    • 2019-11-06
    • 2020-07-12
    • 2019-08-26
    • 2014-12-23
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    相关资源
    最近更新 更多