gpt4 book ai didi

php - 反转字符串中元音的位置

转载 作者:行者123 更新时间:2023-12-05 02:15:56 26 4
gpt4 key购买 nike

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

例子-

“你好”,返回“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"
?>

最佳答案

我稍微修改了你的:

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

关于php - 反转字符串中元音的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50855265/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com