Convert string to palindrome string with minimum insertions

后端 未结 5 613
心在旅途
心在旅途 2020-12-31 14:42

In order to find the minimal number of insertions required to convert a given string(s) to palindrome I find the longest common subsequence of the string(lcs_string) and its

5条回答
  •  一个人的身影
    2020-12-31 14:55

    PHP Solution of O(n)

    function insertNode(&$arr, $idx, $val) {
        $arr = array_merge(array_slice($arr, 0, $idx), array($val), array_slice($arr, $idx));
    }
    function createPalindrome($arr, $s, $e) {
        $i = 0;
        while(true) {
            if($s >= $e) {
                break;
            } else if($arr[$s] == $arr[$e]) {
                $s++; $e--; // shrink the queue from both sides 
                continue;
            } else {
                insertNode($arr, $s, $arr[$e]);
                $s++;
            }
        }
        echo implode("", $arr);
    }
    $arr = array('b', 'e', 'a', 'a', 'c', 'd', 'a', 'r', 'e');
    echo createPalindrome ( $arr, 0, count ( $arr ) - 1 );
    

提交回复
热议问题