透過交換相鄰字串中的字元,使所有字串都成為迴文串
在這個問題中,我們將透過交換相鄰字串的字元,使給定陣列中的所有字串都成為迴文串。
為了解決這個問題,我們將嘗試使所有字串在 p 索引和 str_len - p - 1 索引處的字元相同,只有當 p 索引和 (str_len - p - 1) 索引處的字元總數相同才有可能。
問題陳述 - 我們得到一個包含多個相同長度(等於 N)字串的陣列 arr。我們需要計算使陣列中所有字串都成為迴文串所需的最小操作次數。我們可以在一次操作中交換任意兩個相鄰字串的第 p 個字元。如果不可能使所有字串都成為迴文串,則列印 -1。
示例
輸入
arr = {"57", "65", "76"};
輸出
2
解釋
我們需要交換 '13' 和 '21' 的第二個字元。所以,字串將變成 {“55”, “67”, “76”}
接下來,交換第二個和第三個字串的第一個字元。所以,最終的字串將是 {'55', '77', '66'}。
所有最終字串都是迴文串。
輸入
arr = {"aba", "ppp", "sss"}
輸出
0
解釋 - 由於所有字串都是迴文串,因此我們需要執行 0 次操作。
輸入
arr = {"nnn", "pqr", "rqt"}
輸出
-1
解釋 - 透過交換相鄰字元不可能使所有字串都成為迴文串。
方法 1
為了使任何字串成為迴文串,該字串在 p 索引和 (str_len - p - 1) 索引處應該具有相同的字元。
這裡,我們只能交換相鄰字串中相同索引處的字元。因此,我們可以取每個字串的第 p 個字元並構成一個列表。同樣,我們可以取字串中 (str_len - p - 1) 索引處的字元並構成一個列表。
之後,我們可以交換第二個列表的相鄰字元,以使兩個列表相同。如果我們無法使任何列表相同,我們就無法使所有字串都成為迴文串。
例如,輸入陣列為 {"57", "65", "76"}。
因此,列表將是 p = 0,而 str_len - p - 1 = 1 索引等於 {5, 6, 7} 和 {7, 5, 6}。
在這裡,我們可以交換第二個列表的字元以使列表等於第一個列表。
透過這種方式,我們需要計算從 0 到 len/2 的所有列表所需的移動次數,並將它們加起來以獲得最終輸出。
演算法
步驟 1 - 將 'cnt' 變數初始化為 0 以儲存最終結果。
步驟 2 - 從第 0 個索引到 len/2 索引遍歷字串。
步驟 3 - 在 temp1 列表中,獲取所有第 p 個索引的字元,在 temp2 字串中,透過執行 getColumnChars() 函式獲取所有 (str_len - p - 1) 索引的字元。
步驟 3.1 - 在 getColumnChars() 函式中,初始化 'chars' 列表。
步驟 3.2 - 遍歷陣列的所有字串,訪問從引數作為引數傳遞的索引處的字元,並將其推送到 'chars' 列表中。
步驟 3.3 - 返回 chars 列表。
步驟 4 - 如果 temp1 和 temp2 列表相同,則我們不需要對當前列表執行任何操作。
步驟 5 - 現在,執行 isSwapPossible() 函式以檢查是否可以透過交換字元來使兩個列表相同。
步驟 5.1 - 在 isSwapPossible() 函式中,定義 'freq' 對映以儲存列表字元的頻率。
步驟 5.2 - 遍歷 temp1 列表,併為 freq 對映中的 'ch' 鍵的值加 1。
步驟 5.3 - 遍歷 temp2 列表,併為 freq 對映中的 'ch' 鍵的值減 1。
步驟 5.4 - 遍歷對映,如果任何鍵的值不為零,則返回 false,因為兩個列表不包含相同的字元。
步驟 5.5 - 返回 true。
步驟 6 - 如果 isSwapPossible() 函式返回 false,則將 cnt 更新為 -1,並中斷迴圈。
步驟 7 - 否則,執行 countSwaps() 函式來計算透過交換相鄰字元使兩個列表相同所需的移動次數,並將它的返回值新增到 'cnt' 變數中。
步驟 7.1 - 在 countSwaps() 函式中,將 'sps' 初始化為 0,並開始遍歷第一個列表。
步驟 7.2 - 如果兩個列表中 p 索引處的字元不同,則執行以下步驟。否則,移動到下一個索引。
步驟 7.3 - 如果 p 是最後一個索引,則交換 p - 1 和 p 索引處的字元。否則,交換 p 和 p + 1 索引處的字元。
步驟 7.4 - 將 'sps' 加 1,並將 p 重新初始化為 0。
步驟 7.5 - 返回 'sps' 值。
步驟 8 - 在主函式中返回 cnt 值。
示例
以下是各種程式語言中此操作的實現:
#include <stdio.h>
#include <string.h>
// Function to get character from the ind index of all strings
void getColumnChars(char arr[][100], int rows, int ind, char chars[]) {
for (int i = 0; i < rows; i++) {
chars[i] = arr[i][ind];
}
}
// Function to check if it's possible to swap and make both lists the same
int isSwapPossible(char temp1[], char temp2[], int rows) {
int freq[256] = {0};
// Store frequency of characters of temp1
for (int i = 0; i < rows; i++) {
freq[temp1[i]]++;
}
// Subtract frequency of characters of temp2
for (int i = 0; i < rows; i++) {
freq[temp2[i]]--;
}
for (int i = 0; i < 256; i++) {
// When characters are not the same in both rows, return 0.
if (freq[i] != 0) {
return 0;
}
}
return 1;
}
// Function to count swaps required to make both lists the same
int countSwaps(char temp1[], char temp2[], int rows) {
int sps = 0;
int p = 0;
while (p != rows) {
if (temp1[p] != temp2[p]) {
if (p == rows - 1) {
// For the last character
char temp = temp2[p - 1];
temp2[p - 1] = temp2[p];
temp2[p] = temp;
} else {
// For other characters
char temp = temp2[p];
temp2[p] = temp2[p + 1];
temp2[p + 1] = temp;
}
// Increment number of swaps
sps += 1;
p = 0;
} else {
p += 1;
}
}
return sps;
}
int numberOfSwaps(char arr[][100], int rows, int cols) {
int cnt = 0;
int str_len = cols;
for (int p = 0; p < str_len / 2; p++) {
char temp1[100];
char temp2[100];
getColumnChars(arr, rows, p, temp1);
getColumnChars(arr, rows, str_len - p - 1, temp2);
// When each string contains the same character at p and str_len - p - 1 index
if (memcmp(temp1, temp2, rows) == 0) {
continue;
}
// Check whether possible to make temp1 and temp2 equal by swapping characters
if (!isSwapPossible(temp1, temp2, rows)) {
cnt = -1;
break;
} else {
cnt += countSwaps(temp1, temp2, rows);
}
}
return cnt;
}
int main() {
char arr[][100] = {"57", "65", "76"};
int rows = 3;
int cols = 2;
int result = numberOfSwaps(arr, rows, cols);
printf("The minimum number of swaps required to make all strings palindromic is %d\n", result);
return 0;
}
輸出
The minimum number of swaps required to make all strings palindromic is 2
#include <bits/stdc++.h>
using namespace std;
// Get character from the ind index of all strings
vector<char> getColumnChars(vector<string> arr, int ind) {
vector<char> chars;
for (auto it : arr) {
chars.push_back(it[ind]);
}
return chars;
}
bool isSwapPossible(vector<char> temp1, vector<char> temp2) {
map<char, int> freq;
// Store frequency of characters of temp1
for (auto ch : temp1)
freq[ch]++;
// Subtract frequency of characters of temp2
for (auto ch : temp2)
freq[ch]--;
for (auto ch : freq) {
// When characters are not the same in both rows, return 0.
if (ch.second != 0)
return 0;
}
return 1;
}
int countSwaps(vector<char> temp1, vector<char> temp2) {
int sps = 0;
int p = 0;
while (p != temp1.size()) {
if (temp1[p] != temp2[p]) {
if (p == temp1.size() - 1) {
// For the last character
swap(temp2[p - 1], temp2[p]);
} else {
// For other characters
swap(temp2[p], temp2[p + 1]);
}
// Increment number of swaps
sps += 1;
p = 0;
}
else
p += 1;
}
return sps;
}
int numberOfSwaps(vector<string> arr) {
int cnt = 0;
int str_len = arr[0].size();
for (int p = 0; p < str_len / 2; p++) {
vector<char> temp1 = getColumnChars(arr, p);
vector<char> temp2 = getColumnChars(arr, str_len - p - 1);
// When each string contains the same character at p and str_len - p - 1 index
if (temp1 == temp2) {
continue;
}
// Check whether possible to make temp1 and temp2 equal by swapping characters
if (!isSwapPossible(temp1, temp2)) {
cnt = -1;
break;
} else {
cnt += countSwaps(temp1, temp2);
}
}
return cnt;
}
int main() {
vector<string> arr{"57", "65", "76"};
cout << "The minimum number of swaps required to make all strings palindromic is " << numberOfSwaps(arr) << endl;
}
輸出
The minimum number of swaps required to make all strings palindromic is 2
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Main {
// Function to get character from the ind index of all strings
static char[] getColumnChars(String[] arr, int ind) {
char[] chars = new char[arr.length];
for (int i = 0; i < arr.length; i++) {
chars[i] = arr[i].charAt(ind);
}
return chars;
}
// Function to check if it's possible to swap and make both lists the same
static boolean isSwapPossible(char[] temp1, char[] temp2) {
Map<Character, Integer> freq = new HashMap<>();
// Store frequency of characters of temp1
for (char ch : temp1) {
freq.put(ch, freq.getOrDefault(ch, 0) + 1);
}
// Subtract frequency of characters of temp2
for (char ch : temp2) {
freq.put(ch, freq.getOrDefault(ch, 0) - 1);
}
for (int value : freq.values()) {
// When characters are not the same in both rows, return false.
if (value != 0) {
return false;
}
}
return true;
}
// Function to count swaps required to make both lists the same
static int countSwaps(char[] temp1, char[] temp2) {
int sps = 0;
int p = 0;
while (p != temp1.length) {
if (temp1[p] != temp2[p]) {
if (p == temp1.length - 1) {
// For the last character
char temp = temp2[p - 1];
temp2[p - 1] = temp2[p];
temp2[p] = temp;
} else {
// For other characters
char temp = temp2[p];
temp2[p] = temp2[p + 1];
temp2[p + 1] = temp;
}
// Increment number of swaps
sps += 1;
p = 0;
} else {
p += 1;
}
}
return sps;
}
static int numberOfSwaps(String[] arr) {
int cnt = 0;
int str_len = arr[0].length();
for (int p = 0; p < str_len / 2; p++) {
char[] temp1 = getColumnChars(arr, p);
char[] temp2 = getColumnChars(arr, str_len - p - 1);
// When each string contains the same character at p and str_len - p - 1 index
if (Arrays.equals(temp1, temp2)) {
continue;
}
// Check whether possible to make temp1 and temp2 equal by swapping characters
if (!isSwapPossible(temp1, temp2)) {
cnt = -1;
break;
} else {
cnt += countSwaps(temp1, temp2);
}
}
return cnt;
}
public static void main(String[] args) {
String[] arr = {"57", "65", "76"};
int result = numberOfSwaps(arr);
System.out.println("The minimum number of swaps required to make all strings palindromic is " + result);
}
}
輸出
The minimum number of swaps required to make all strings palindromic is 2
# Function to get character from the ind index of all strings
def get_column_chars(arr, ind):
chars = []
for s in arr:
chars.append(s[ind])
return chars
# Function to check if it's possible to swap and make both lists the same
def is_swap_possible(temp1, temp2):
freq = {}
# Store frequency of characters of temp1
for ch in temp1:
freq[ch] = freq.get(ch, 0) + 1
# Subtract frequency of characters of temp2
for ch in temp2:
freq[ch] = freq.get(ch, 0) - 1
# When characters are not the same in both rows, return false.
for value in freq.values():
if value != 0:
return False
return True
# Function to count swaps required to make both lists the same
def count_swaps(temp1, temp2):
sps = 0
p = 0
while p != len(temp1):
if temp1[p] != temp2[p]:
if p == len(temp1) - 1:
temp2[p - 1], temp2[p] = temp2[p], temp2[p - 1]
else:
temp2[p], temp2[p + 1] = temp2[p + 1], temp2[p]
sps += 1
p = 0
else:
p += 1
return sps
def number_of_swaps(arr):
cnt = 0
str_len = len(arr[0])
for p in range(str_len // 2):
temp1 = get_column_chars(arr, p)
# When each string contains the same character at p and str_len - p - 1 index
temp2 = get_column_chars(arr, str_len - p - 1)
if temp1 == temp2:
continue
if not is_swap_possible(temp1, temp2):
cnt = -1
break
else:
cnt += count_swaps(temp1, temp2)
return cnt
if __name__ == "__main__":
arr = ["57", "65", "76"]
result = number_of_swaps(arr)
print(f"The minimum number of swaps required to make all strings palindromic is {result}")
輸出
The minimum number of swaps required to make all strings palindromic is 2
時間複雜度 - O(M*N*N),其中 O(M) 用於遍歷陣列,O(N*N) 用於使所有字串都成為迴文串。
空間複雜度 - O(N) 用於在對映中儲存字元頻率。
我們學習瞭如何計算使陣列中所有字串都成為迴文串所需的交換次數。邏輯部分是準備 p 和 str_len - p - 1 索引的字元列表,並使列表相同。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP