最小化將字元替換為其最近的字母以使字串成為迴文


在本文中,我們將討論一個引人入勝的演算法問題:“最小化將字元替換為其最近的字母以使字串成為迴文”。這個問題很有趣,因為它涉及字串操作、迴文檢查以及字元的 ASCII 值的概念。讓我們深入探討這個問題。

問題陳述

給定一個字元字串,任務是將其轉換為迴文,並使替換次數最少。這些替換是透過將字元更改為其最近的字母來完成的。

理解問題

迴文是指正讀和反讀都一樣的單詞、短語、數字或其他字元序列。我們的目標是最小化將給定字串轉換為迴文所需的總替換次數。

例如,考慮字串“abc”。為了將其轉換為迴文,我們可以將“c”替換為“a”,這需要兩次替換(“c”到“b”和“b”到“a”)。因此,最小替換次數為 2。

演算法方法

為了解決這個問題,我們將使用雙指標方法。以下是步驟 -

  • 初始化兩個指標,一個位於字串的開頭,另一個位於字串的末尾。

  • 比較指標處的字元。

  • 如果它們相等,則將指標向內移動。

  • 如果它們不相等,則將距“a”較遠的字元替換為較近的字元,並將替換計數加 1。此外,將指標向內移動。

  • 重複步驟 2-4,直到起始指標不小於結束指標。

示例

以下是實現上述方法的程式 -

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int makePalindrome(char* str) {
   int len = strlen(str);
   int res = 0;
   
   // Loop through the string from both ends and calculate the absolute difference between characters
   // Add the absolute difference to the result
   for (int i = 0, j = len - 1; i < j; i++, j--) {
      res += abs(str[i] - str[j]);
   }
   return res;
}

// Main function to test the makePalindrome function
int main() {
   char str[] = "abcde";
   printf("Minimum replacements: %d\n", makePalindrome(str));
   return 0;
}

輸出

Minimum replacements: 6
#include<bits/stdc++.h>
using namespace std;

int makePalindrome(string str) {
   int len = str.size();
   int res = 0;
   for (int i = 0, j = len - 1; i < j; i++, j--) {
      res += abs(str[i] - str[j]);
   }
   return res;
}

int main() {
   string str="abcde";
   cout << "Minimum replacements: " << makePalindrome(str);
   return 0;
}

輸出

Minimum replacements: 6
import java.util.Scanner;

public class Main {
   public static int makePalindrome(String str) {
      int len = str.length();
      int res = 0;
       
      // Loop through the string from both ends and calculate the absolute difference between characters
      // Add the absolute difference to the result
      for (int i = 0, j = len - 1; i < j; i++, j--) {
         res += Math.abs(str.charAt(i) - str.charAt(j));
      }
      return res;
   }

   // Main function to test the makePalindrome function
   public static void main(String[] args) {
      String str = "abcde";
      System.out.println("Minimum replacements: " + makePalindrome(str));
   }
}

輸出

Minimum replacements: 6
def make_palindrome(s):
   n = len(s)
   res = 0
   
   # Loop through the string from both ends and calculate the absolute difference between characters
   # Add the absolute difference to the result
   for i in range(n // 2):
      res += abs(ord(s[i]) - ord(s[n - i - 1]))
   return res

# Main function to test the make_palindrome function
def main():
   s = "abcde"
   print("Minimum replacements:", make_palindrome(s))

if __name__ == "__main__":
   main()

輸出

Minimum replacements: 6

測試用例示例

讓我們執行一個示例 -

考慮字串“abcde”。上述程式將輸出“最小替換次數:4”。原因如下 -

  • 比較“a”和“e”。它們不相等,因此將“e”替換為“a”。這需要 4 次替換。我們的字串現在是“abcda”。

  • 比較“b”和“d”。它們不相等,因此將“d”替換為“b”。這需要 2 次替換。我們的字串現在是“abcba”。

  • 現在,字串是一個迴文。因此,總的最小替換次數為 4 + 2 = 6。

請記住,替換次數計算為字元的 ASCII 值的絕對差。

結論

這個問題是簡單字串操作和雙指標技術如何解決相對複雜問題的極好示例。理解此類問題不僅有助於編碼面試,還有助於提高整體解決問題的能力。

更新於: 2023年10月23日

319 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告