在这个问题中,我们需要找到数组中的最后一个回文字符串。如果任何字符串在读取时相同,无论是从头开始读取还是从末尾开始读取,都可以说该字符串是回文。我们可以比较起始字符和结束字符来检查特定字符串是否是回文。查找回文字符串的另一种方法是将字符串反转并与原始字符串进行比较。
问题陈述 - 我们给定一个长度为n的数组,其中包含不同的字符串。我们需要找到给定数组中的最后一个回文字符串。
示例例子输入– arr[] = {werwr, rwe, nayan, tut, rte};
输出 – ‘tut’
explanation– 给定数组中的最后一个回文字符串是‘tut’。
输入– arr[] = {werwr, rwe, nayan, acd, sdr};
输出-“nayan”
explanation – ‘nayan’是给定数组中的最后一个回文字符串。
输入– arr[] = {werwr, rwe, jh, er, rte};
输出-“”
说明 – 由于数组不包含任何回文字符串,因此它会打印空字符串。
方法 1在这种方法中,我们将从头开始遍历数组并将最后一个回文字符串存储在变量中。另外,我们还会比较字符串的开头和结尾字符,以检查字符串是否是回文。
算法定义变量‘lastpal’来存储最后一个回文字符串。
遍历数组。
使用ispalindrome()函数来检查数组中第pth索引处的字符串是否是回文。
在ispalindrome()函数中,使用循环遍历字符串。
比较 str[i] 和 str[len - p - 1] 字符;如果有任何字符不匹配,则返回 false。
循环的所有迭代完成后返回 true。
如果当前字符串是回文,使用当前字符串更新‘lastpal’变量的值。
返回“lastpal”。
示例#include <bits/stdc++.h>using namespace std;bool ispalindrome(string &str) { int size = str.length(); for (int p = 0; p < size / 2; p++) { // compare first ith and last ith character if (str[p] != str[size - p - 1]) { return false; } } return true;}string lastpalindrome(string arr[], int n) { string lastpal = ; for (int p = 0; p < n; p++) { if (ispalindrome(arr[p])) { // if the current string is palindrome, then update the lastpal string lastpal = arr[p]; } } return lastpal;}int main() { string arr[] = {werwr, rwe, nayan, abba, rte}; int n = sizeof(arr)/sizeof(arr[0]); cout << the last palindromic string in the given array is << lastpalindrome(arr, n); return 0;}
输出the last palindromic string in the given array is abba
时间复杂度 - o(n*k),因为我们遍历数组并检查每个字符串是否是回文。
空间复杂度 - o(1),因为我们使用的是常量空间。
方法2在这种方法中,我们将从最后一个开始遍历数组,当我们找到最后一个回文字符串时,我们将返回它。另外,我们使用reverse()方法来检查字符串是否是回文。
算法从最后一个开始遍历数组。
使用ispalindrome()函数来检查字符串是否是回文。
在ispalindrome()函数中,将'str'字符串存储在'temp'变量中。
使用reverse()方法反转临时字符串。
如果str和temp相等,则返回true。否则,返回false。
如果第i个索引处的字符串是回文,则返回该字符串。
示例#include <bits/stdc++.h>using namespace std;bool ispalindrome(string &str) { string temp = str; reverse(temp.begin(), temp.end()); return str == temp;}string lastpalindrome(string array[], int n) { for (int p = n - 1; p >= 0; p--) { if (ispalindrome(array[p])) { return array[p]; } } // return a default value if no palindrome is found return no palindromic string found;}int main() { string arr[] = {werwr, rwe, nayan, tut, rte}; int n = sizeof(arr) / sizeof(arr[0]); cout << the last palindromic string in the given array is << lastpalindrome(arr, n); return 0;}
输出the last palindromic string in the given array is tut
时间复杂度 - o(n*k),因为我们遍历数组并反转字符串。
空间复杂度 - o(1),因为我们不使用动态空间。
在这里,我们学习了两种方法来找到给定数组中的最后一个回文字符串。这两种方法的时间和空间复杂度几乎相似,但第二个代码比第一个更易读且更好。
此外,程序员可以尝试在给定数组中查找倒数第二个字符串并进行更多练习。
以上就是在给定的数组中找到最后一个回文字符串的详细内容。