为您提供了长度为n的字符串str。打印字符串中每个元素的位置,以便可以形成回文,否则在屏幕上显示消息“无回文”。
回文是一个单词的字符序列,从正向或反向或反向读取,例如MADAM,赛车。
为了找到序列或单词是回文,我们通常将单词的反向存储在单独的字符串中,如果两者相同,则比较两者,则给定的单词或序列是回文。但是在这个问题上,我们必须打印出在回文中制作单词或序列的安排。
像这样,有一个字符串str =“ tinni”,那么它可以是intni或nitin,因此我们必须返回排列顺序中的任何一个,因为索引从1开始,结果可以是2 3 1 4 5或3 2 1 5两者中的4个。
上面的问题需要像下面给出的例子一样的解决方案-
Input: string str = “baa” Output: 2 1 3 Input: string str = “tinni” Output: 2 3 1 4 5
void printPalindromePos(string &str) START STEP 1: DECLARE vector<int> pos[MAX] STEP 2: DECLARE AND ASSIGN n WITH LENGTH OF str STEP 3: LOOP FOR i = 0 AND i < n AND i++ pos[str[i]].push_back(i+1) END LOOP STEP 4: SET oddCount = 0 STEP 5: DECLARE oddChar STEP 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 IF END FOR STEP 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 LOOP END LOOP STEP 9: IF oddCount > 0 THEN, DECLARE AND SET last = pos[oddChar].size() - 1 PRINT pos[oddChar][last] SET pos[oddChar].pop_back(); END IF STEP 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;
//给出最大字符数
const int MAX = 256;
void printPalindromePos(string &str){
   //在给定的字符串中插入字符的所有位置。
   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] << " ";
   }
   //考虑一个实例的奇数字符
   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