为您提供了一个长度为 n 的字符串 str。打印字符串中每个元素的位置,以便它可以形成回文,否则在屏幕上打印消息“no palindrome”。
什么是回文?palindrome 是一个单词,从反向或向后读取的字符序列与从正向读取的字符序列相同,例如 madam、racecar。
要查找序列或单词是回文,我们通常将单词的反向存储在单独的字符串中并比较两者,如果它们相同,则给定的单词或序列是回文。但是在这个问题中,我们必须打印排列以形成回文中的单词或序列。
就像,有一个字符串 str = “tinni” 那么它可以是 intni 或 nitin 所以我们必须返回作为从 1 开始的索引和结果的任何一个排列顺序可以是 2 3 1 4 5 或 3 2 1 5 4 两者中的一个。
上述问题需要像下面给出的示例那样的解决方案-
示例input: string str = “baa”output: 2 1 3input: string str = “tinni”output: 2 3 1 4 5
算法void printpalindromepos(string &str)startstep 1: declare vector<int> pos[max]step 2: declare and assign n with length of strstep 3: loop for i = 0 and i < n and i++ pos[str[i]].push_back(i+1)end loopstep 4: set oddcount = 0step 5: declare oddcharstep 6: loop for i=0 and i<max and i++ if pos[i].size() % 2 != 0 then, increment oddcount by 1 set oddchar as i end ifend forstep 7: if oddcount > 1 then, print "no palindrome"step 8: loop for i=0 and i<max and i++ decrlare mid = pos[i].size()/2 loop for j=0 and j<mid and j++ print pos[i][j] end loopend loopstep 9: if oddcount > 0 then, declare and set last = pos[oddchar].size() - 1 print pos[oddchar][last] set pos[oddchar].pop_back();end ifstep 10: loop for i=max-1 and i>=0 and i-- declare and set count = pos[i].size() loop for j=count/2 and j<count and j++ print pos[i][j]stop
示例#include <bits/stdc++.h>using namespace std;// giving the maximum charactersconst int max = 256;void printpalindromepos(string &str){ //inserting all positions of characters in the given string. vector<int> pos[max]; int n = str.length(); for (int i = 0; i < n; i++) pos[str[i]].push_back(i+1); /* find the number of odd elements.takes o(n) */ int oddcount = 0; char oddchar; for (int i=0; i<max; i++) { if (pos[i].size() % 2 != 0) { oddcount++; oddchar = i; } } /* palindrome can't contain more than 1 odd characters */ if (oddcount > 1) cout << "no palindrome"; /* print positions in first half of palindrome */ for (int i=0; i<max; i++){ int mid = pos[i].size()/2; for (int j=0; j<mid; j++) cout << pos[i][j] << " "; } // consider one instance odd character if (oddcount > 0){ int last = pos[oddchar].size() - 1; cout << pos[oddchar][last] << " "; pos[oddchar].pop_back(); } /* print positions in second half of palindrome */ for (int i=max-1; i>=0; i--){ int count = pos[i].size(); for (int j=count/2; j<count; j++) cout << pos[i][j] << " "; }}int main(){ string s = "tinni"; printpalindromepos(s); return 0;}
输出如果我们运行上面的程序,那么它将生成以下输出 -
2 3 1 4 5
以上就是打印出排列好的字符位置,以使其成为回文的c程序的详细内容。