在字符串中反转元音字母的位置

3

我想要反转字符串中元音字母的顺序。我已经编写了下面的代码,但结果为空集。

例如 -

"hello",返回 "holle"

"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"
?>
6个回答

3

我稍微修改了你的内容:

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

1

这是已更改并运行的代码:

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>";

1

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

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');

输出:

那只快速棕色的狐狸跳过了懒惰的狗

好问题!


0

试试这个简单的方法,

<?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;


?>

0
只要您只处理单字节字符的字符串,就可以使用数组语法基于偏移量进行替换。
首先,生成一个元音字母的数组,并告诉 preg_match_all() 存储它们的原始偏移量/位置。
然后迭代匹配的元音字母数组,并从左到右用元音字母从右到左替换元音字母的位置。
如果您不熟悉 PREG_OFFSET_CAPTURE 标志,请使用 var_export($m) 查看生成的多维数组。
代码:(演示) (带有表达式变量的演示)
$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',
)

0

这里有另一个可行的解决方案

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接