【问题标题】:Reverse position of vowels in a string反转元音在字符串中的位置
【发布时间】:2018-06-14 10:26:29
【问题描述】:

我想颠倒字符串中元音的顺序。我写了下面的代码,但是结果集是空的。

例子-

“你好”,返回“你好”

“leetcode”,返回“leotcede”

帮助我实现这一目标。

<?php
function reverseVowels($string) {

    $result = '';
    
    $string = array();
    $vowels = array();
    
    $strlength = count($string);
    for ($i=0; $i < $strlength; $i++) {
        $orig = $strlength[$i];
        $char =  strtolower($strlength[$i]);

        if ($char === 'a' || $char === 'e' || $char === 'i' || $char === 'o' || $char === 'u') {
            array_push($vowels, $orig);
            $orig = null; 
        }
        
         array_push($string, $orig);
       
    }
    $new_strlength = count($string);
    
    for ($i=0; $i < $new_strlength; $i++) {
        if (!$string[$i]) {
            $string[$i] = array_splice($vowels, count($vowels) - 1, 1);
        }
    }
    
    $result = $string;
    return $result;
  
}

$res = reverseVowels("hello hello");
print_r($res);

//"hello", return "holle"
//"leetcode", return "leotcede"
?>

【问题讨论】:

    标签: php replace reverse offset


    【解决方案1】:

    我稍微修改了你的:

    function reverseVowels($string)
    {
        $result = '';
        $out    = [];
        $vowels = [];
    
        $len = strlen($string);
    
        for ($i=0; $i < $len; $i++) {
            $orig = $string[$i];
            $char = strtolower($string[$i]);
            if (in_array($char, ['a','e','i','o','u'])) {
                $vowels[] = $orig;
                $orig = null; 
            }
            $out[] = $orig;
        }
    
        for ($i=0, $j=count($vowels)-1; $i < $len; $i++)
            $result .= $out[$i] == null
                ? $vowels[$j--]
                : $out[$i];
    
        return $result;
    }
    

    也可以使用数组函数:

    function reverse_vowels(string $str)
    {
        $vowels       = ['a','e','i','o','u'];
        $replacements = [];
        $chars        = str_split($str);
        $replacements = array_intersect($chars, $vowels);
        $replacements = array_combine(
            array_keys($replacements),
            array_reverse($replacements)
        );
        $chars  = array_replace($chars, $replacements);
    
        return implode('', $chars);
    }
    
    echo reverse_vowels('stackoverflow');
    

    输出:

    stockevorflaw
    

    【讨论】:

      【解决方案2】:

      这是更改后的工作代码:

      function reverseVowels($str) {
        $result = '';
          $string = array();
          $vowels = array();
          $strlength = count($str);
          for ($i=0; $i < strlen($str); $i++) {
              $orig = $str[$i];
              $char =  strtolower($str[$i]);
              if ($char === 'a' || $char === 'e' || $char === 'i' || $char === 'o' || $char === 'u') {
                  array_push($vowels, $orig);
                  $orig = null; 
              }
               array_push($string, $orig);
          }
          $new_strlength = count($string);
          for ($i=0; $i < count($string); $i++) {
              if (!$string[$i]) {
                  $string[$i] = array_splice($vowels, count($vowels) - 1, 1)[0];
              }
          }
          $result = $string;
          return $result;
      }
      $res = reverseVowels("leetcode");
      echo "<pre>";
      print_r($res);
      echo "</pre>";
      

      【讨论】:

        【解决方案3】:

        我喜欢函数式风格 - 它生成最短的代码。所以这里是:

        function reverse_vowels($word) {
            $vowels = implode(array_filter(str_split($word),
                      function ($c) {return preg_match('/[aeiou]/i', $c);}));
            $v = 0;
            $reverse = implode(array_map(
                      function ($i) use ($word, $vowels, &$v) {
                         $is_vowel = preg_match('/[aeiou]/i', $word[$i]);
                         return $is_vowel ? $vowels[strlen($vowels) - 1 - $v++] : $word[$i];
                      }, range(0, strlen($word) - 1)));
            return $reverse;
        }
        
        echo reverse_vowels('The quick brown fox jumps over the lazy dog');
        

        输出:

        Tho qaeck brewn fox 跳到 thi luzy deg

        好问题!

        【讨论】:

          【解决方案4】:

          试试这个简单的方法,

          <?php
          
          $str = "leetcode";
          $v = array("a","e","i","o","u");
          
          
          $replace = array();
          
          for($i=0;$i<strlen($str);$i++){
              if(in_array($str[$i],$v))
              $replace[$i] = $str[$i];
          }
          
          $replaceIndex = array_reverse(array_keys($replace));
          $replaceValue = array_values($replace);
          $replace = array_combine($replaceIndex,$replaceValue);
          
          foreach($replace as $key=>$value){
            $str[$key] = $replace[$key];
          }
          
          echo $str;
          
          
          ?>
          

          【讨论】:

            【解决方案5】:

            这是另一个可以正常工作的解决方案

            function solution($str) {
                $vowels = [];
                $strArr = str_split($str);
                foreach ($strArr as $char) {
                  if (in_array($char, ['a','e','i','o','u']) && !in_array($char, $vowels)) {
                    $vowels[] = $char;
                  }
                }
                $result = "";
                foreach ($strArr as $char) {
                  $pos = array_search($char, $vowels);
                  if ($pos === false) {
                    $result .= $char;
                    continue;
                  }
                  if ($pos == 0) {
                    $result .= $vowels[1];
                    continue;
                  }
                  if ($pos == 1) {
                    $result .= $vowels[0];
                    continue;
                  }
                  if ($pos % 2 == 0 && array_key_exists(($pos+1), $vowels)) {
                    $result .= $vowels[$pos+1];
                    continue;
                  }
                  if ($pos % 2 == 0 && !array_key_exists(($pos+1), $vowels)) {
                    $result .= $vowels[$pos];
                    continue;
                  }
                  if ($pos % 2 != 0) {
                    $result .= $vowels[$pos-1];
                    continue;
                  }
                }
                return $result;
            }
            

            从我的存储库中提取https://github.com/sodmond/vowel_reversal

            【讨论】:

              【解决方案6】:

              只要你只处理单字节字符的字符串,你就可以使用数组语法根据偏移量进行替换。

              首先,生成一个元音数组并告诉preg_match_all() 存储它们的原始偏移/位置。

              然后迭代匹配的元音数组,用从左到右的元音替换从右到左的元音位置。

              如果您不熟悉PREG_OFFSET_CAPTURE 标志,请使用var_export($m) 查看生成的多维数组。

              代码:(Demo) (Demo with expressive variables)

              $strings = [
                  'hello',
                  'leetcode',
                  'atwood'
              ];
              
              foreach ($strings as &$string) {
                  $count = preg_match_all('~[aeiou]~', $string, $m, PREG_OFFSET_CAPTURE);
                  for ($i = 1; $i <= $count; ++$i) {
                      $string[$m[0][$count - $i][1]] = $m[0][$i - 1][0];
                  }
              }
              var_export($strings);
              

              输出:

              array (
                0 => 'holle',
                1 => 'leotcede',
                2 => 'otwoad',
              )
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2017-03-30
                • 1970-01-01
                • 2013-02-08
                • 1970-01-01
                • 2022-09-23
                • 2021-12-01
                相关资源
                最近更新 更多