繁体   English   中英

如何使用字符串操作解决“解码字符串问题”?

[英]How can I solve "decode string problem" using string manipulation?

我遇到了Decode string problem ,它给出了一个编码字符串 s,使用规则对其进行解码:
N[encoded] => encoded*N

例子

$input = "4[abc]";
// output: abcabcabcabc

$input = "ac3[ab]d";
// output: acabababd

$input = "a2[b3[cd]]";
// output: abcdcdcdbcdcdcd

我已经尝试使用带有 if 条件的字符串操作来解决它,它仅适用于两个输入,但是当给定的输入具有多个编码字符串时,它最后一个失败。

$output = '';
$arr = str_split($input);
for ($i=0; $i < count($arr); $i++) { 
    $char = $arr[$i];//current character
    if($char == '['){
        $closed = strpos($input, ']');
        $len = $closed - ($i+1);
        $output .= str_repeat(substr($input, $i+1, $len), $prev);
        $i = strpos($input, ']');
    }elseif(ctype_digit($char)){
        $prev = $char;
    }else{
        $output .= $char;
    }
}
echo $output;

有什么方法可以使用这种方法或其他方法来解决它。 还是只能使用堆栈来解决? 感谢您的任何想法可以帮助解决这个问题!

要解决嵌套[],你必须从内到外解码。 该解决方案使用 preg_replace_callback 直到没有任何东西可以替换。

function fkdecode($str){
  while(true){
  $newStr = preg_replace_callback('~(\d+)\[([^\[\]]+)\]~',
    function($m){
      return str_repeat($m[2],(int)$m[1]);
    },
    $str);
   if($newStr == $str) break;
   $str = $newStr;
  }
  return $str;
}

//test
$inputs = ["4[abc]", // output: abcabcabcabc
 "ac3[ab]d", // output: acabababd
 "a2[b3[cd]]", // output: abcdcdcdbcdcdcd
];

foreach($inputs as $input){
  echo $input.' := '. fkdecode($input)."<br>\n";
}

Output:

4[abc] := abcabcabcabc
ac3[ab]d := acabababd
a2[b3[cd]] := abcdcdcdbcdcdcd

使用strpos()指定偏移量(在您的情况下$i )来解码多个编码字符串。

您可以使用 strlen 而不是 count。 这是为了避免数组到字符串的转换错误。 此外,您应该考虑N > 9 的情况。

$output = '';

for ($i = 0; $i < strlen($input); $i++) { 
    $char = $input[$i];//current character
    if($char == '['){
        $closed = strpos($input, ']', $i);
        $len = $closed - ($i+1);
        $output .= str_repeat(substr($input, $i+1, $len), $prev);
        $i = strpos($input, ']', $i);
    }elseif(ctype_digit($char)){
        $end = strpos($input, '[', $i);
        $len = $end - $i;
        $prev = substr($input, $i, $len);
        $i = strpos($input, '[', $i) - 1;
    }else{
        $output .= $char;
    }
}

echo $output;
?>

顺便说一句,这不能解决嵌套的[] 您可以使用堆栈来解决它。 提示:检查$closed之前是否有[ 或者使用这种非 O(n) 方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM