簡體   English   中英

如何使用最少的字符替換次數將字符串轉換為回文,以便回文字符串包含給定的單詞?

[英]How to convert a string to a palindrome with minimum number of character replacement such that palindromic string contains a given word?

我們有一個字符串s ,包含小寫字母(az)。 我們可以用任何其他角色替換任何角色,我們可以多次這樣做。

我們可以從s創建一個回文字符串p ,這樣p包含給定的特定單詞(即讓我們假設為linkedin )。 現在,我們需要找到將字符串s轉換為p所需的最少插入次數。

ex - s = linkedininininin然后palindrom字符串p將是linkedinnideknil ,結果將是6。

第二個例子(以使其更清楚) - s = linkaeiouideknil然后p = linkedinnideknil和結果將是4,因為我們將替換aeedoun

我試圖通過取s和L的LCS並從s的長度中減去它來解決它。 但問題是我如何確保回文保證包含給定的單詞(Linkedin)?

請提供您的方法。 謝謝。

假設我理解你的問題,

你可以創建回文,然后在s替換錯誤的字母:

String s="linkaeiouideknil";
String p="";
String word="linkedin";
char[] wordC = word.toCharArray();
StringBuilder sb = new StringBuilder();
sb.append(word);
String drow = sb.reverse().toString();
sb.reverse();
sb.append(drow);
String pali=sb.toString();
char[] sC = s.toCharArray();
sC=Arrays.copyOf(sC, pali.length());
sb.delete(0, sb.length());
int counter=0;
for (int i = 0; i < sC.length; i++) {
    if(sC[i]!=pali.charAt(i)){
        sC[i]=pali.charAt(i);
        counter++;
    }
    sb.append(sC[i]);
}
System.out.println(counter);    
p=sb.toString();
System.out.println(p);

運行時的輸出為4。

我會同時迭代弦樂和回文; 插入輸入字符串中不存在的字符,並在有下一個可用字符時替換子字符串:

public int palindromify(String pal, String read) {
    StringBuilder sb = new StringBuilder(read);
    int insertions = 0; //track insertions
    int palIndex = 0; //our progress through the palindrome
    //caches characters we know aren't further in the input, saves time
    Set<Character> none = new HashSet<>();
    boolean outOfInput = false;
    for (int i = 0;; i++) {
        if (i >= sb.length()) {
            outOfInput = true; //if we run out of input, we know we have to append remainder
            break;
        }
        if (palIndex >= pal.length()) {
            sb.delete(i, sb.length()); //remove remainder, we're out of palindrome
            break;
        }
        char curr = pal.charAt(palIndex++); //increment palindrome
        if (sb.charAt(i) != curr) {
            //perform lookahead
            boolean found = false;
            if (!none.contains(curr)) { //only search a missing char once
                for (int w = i + 1; w < sb.length(); w++) {
                    if (sb.charAt(w) == curr) {
                        sb.replace(i, w + 1, "" + curr); //replace up to our lookahead
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    none.add(curr);
                }
            }
            if (!found) {
                //simply insert our character, later ones are useful for others
                sb.insert(i, curr);
                insertions++; //this was an insertion, one of our counted values
            }
        }
    }
    //if we ran out of input, append the rest of palindrome
    return insertions + (outOfInput ? pal.length() - sb.length() : 0);
}

這可以節省大量的復制/迭代/不必要的工作,並且應該確保最大迭代量是讀取回文的長度(或輸入的長度,以較短者為准)

因此在致電時:

palindromify("linkedinnideknil", "linkedinininin"); //prints '4'

創建實際的回文很容易,而且工作少得多:

String s = /* some value */;
s += new StringBuilder(s).reverse();

編輯:不適用於某些邊緣情況,修復。

我首先要創建你想要將你的字符串轉換成的回文。 接下來,計算從原始字符串到您創建的回文的編輯距離,其中您的編輯正在替換字符串中的字符:無插入或刪除。 代碼看起來像

def minReplacements(original, palindrome, m, n):
    # base case:  we're finished processing either string so we're done
    if (m == 0 or n == 0):
        return 0

    # The characters in the string match so find out how many replacements are
    # required for the remaining characters in the strings.
    if (original[m-1] == palindrome[n-1]):
        return minReplacements(origininal, palindrome, m-1, n-1)

    # Recurse on replacing a character in the original string
    # with a character in the palindrome string
    return 1 + minReplacements(origininal, palindrome, m-1, n-1)

另一方面,如果您想知道將原始字符串轉換為回文字符串需要多少字符替換,插入或刪除,請使用以下代碼更改上面代碼的最后一行:

    return 1 + min(minReplacements(origininal, palindrome, m, n-1),   # insert character
                   minReplacements(origininal, palindrome, m-1, n-1), # replace character
                   minReplacements(origininal, palindrome, m-1, n))   # delete character

然后代碼看起來像:

def minReplacements(original, palindrome, m, n):
    # base case:  we're finished processing either string so we're done
    if (m == 0):  # done processing original string
        return n  # return the number of characters left in palindrome
    if (n == 0):  # done processing palindrome
        return m  # return the number of characters left in the original string

    # The characters in the string match so find out how many edits are
    # required for the remaining characters in the strings.
    if (original[m] == palindrome[n]):
        return minReplacements(origininal, palindrome, m-1, n-1)

    # Recurse on editing a character in the original string
    # with a character in the palindrome string
    return 1 + min(minReplacements(origininal, palindrome, m, n-1),   # insert character
                   minReplacements(origininal, palindrome, m-1, n-1), # replace character
                   minReplacements(origininal, palindrome, m-1, n))   # delete character

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM