📌  相关文章
📜  检查给定的字符串是否奇怪回文 | 2套

📅  最后修改于: 2021-09-02 06:34:37             🧑  作者: Mango

给定字符串str ,任务是检查str奇数索引处的字符是否形成回文字符串。如果不是,则打印“否”,否则打印“是”

例子:

朴素的方法:请参阅本文的第 1 组以了解朴素的方法

有效的方法:这个想法是检查通过附加给定字符串的奇数索引形成的oddString 是否形成回文。因此,我们可以使用堆栈来优化运行时间,而不是创建oddString 然后检查回文。以下是步骤:

  1. 对于检查oddString是回文,我们需要将字符串上半年的奇数索引字符字符串下半年的奇怪的字符进行比较。
  2. 将字符串前半部分的奇数索引字符推入堆栈。
  3. 要将后半部分的奇数索引字符与前半部分进行比较,请执行以下操作:
    • 从堆栈中弹出字符并将其与字符串后半部分的下一个奇数索引字符匹配。
    • 如果上述两个字符不相等,则由奇数索引形成的字符串不是回文的。打印“NO”并中断循环。
    • Else 匹配字符串后半部分的每个剩余奇数字符。
  4. 最后,我们需要检查堆栈的大小是否为零。如果是,则由奇数索引形成的字符串将是回文,否则不是。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check if string formed
// by odd indices is palindromic or not
bool isOddStringPalindrome(
    string str, int n)
{
    int oddStringSize = n / 2;
 
    // Check if length of OddString
    // odd, to consider edge case
    bool lengthOdd
        = ((oddStringSize % 2 == 1)
               ? true
               : false);
 
    stack s;
 
    int i = 1;
    int c = 0;
 
    // Push odd index character of
    // first  half of str in stack
    while (i < n
           && c < oddStringSize / 2) {
        s.push(str[i]);
        i += 2;
        c++;
    }
 
    // Middle element of odd length
    // palindromic string is not
    // compared
    if (lengthOdd)
        i = i + 2;
 
    while (i < n && s.size() > 0) {
        if (s.top() == str[i])
            s.pop();
        else
            break;
        i = i + 2;
    }
 
    // If stack is empty
    // then return true
    if (s.size() == 0)
        return true;
 
    return false;
}
 
// Driver Code
int main()
{
    int N = 10;
 
    // Given string
    string s = "aeafacafae";
 
    if (isOddStringPalindrome(s, N))
        cout << "Yes\n";
    else
        cout << "No\n";
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check if String formed
// by odd indices is palindromic or not
static boolean isOddStringPalindrome(String str,
                                     int n)
{
    int oddStringSize = n / 2;
 
    // Check if length of OddString
    // odd, to consider edge case
    boolean lengthOdd = ((oddStringSize % 2 == 1) ?
                                   true : false);
 
    Stack s = new Stack();
 
    int i = 1;
    int c = 0;
 
    // Push odd index character of
    // first half of str in stack
    while (i < n && c < oddStringSize / 2)
    {
        s.add(str.charAt(i));
        i += 2;
        c++;
    }
 
    // Middle element of odd length
    // palindromic String is not
    // compared
    if (lengthOdd)
        i = i + 2;
 
    while (i < n && s.size() > 0)
    {
        if (s.peek() == str.charAt(i))
            s.pop();
        else
            break;
        i = i + 2;
    }
 
    // If stack is empty
    // then return true
    if (s.size() == 0)
        return true;
 
    return false;
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 10;
 
    // Given String
    String s = "aeafacafae";
 
    if (isOddStringPalindrome(s, N))
        System.out.print("Yes\n");
    else
        System.out.print("No\n");
}
}
 
// This code is contributed by Rohit_ranjan


Python3
# Python3 program for the above approach
 
# Function to check if string formed
# by odd indices is palindromic or not
def isOddStringPalindrome(str, n):
     
    oddStringSize = n // 2;
  
    # Check if length of OddString
    # odd, to consider edge case
    lengthOdd = True if (oddStringSize % 2 == 1) else False
  
    s = []
  
    i = 1
    c = 0
  
    # Push odd index character of
    # first  half of str in stack
    while (i < n and c < oddStringSize // 2):
        s.append(str[i])
        i += 2
        c += 1
  
    # Middle element of odd length
    # palindromic string is not
    # compared
    if (lengthOdd):
        i = i + 2
  
    while (i < n and len(s) > 0):
        if (s[len(s) - 1] == str[i]):
            s.pop()
        else:
            break
         
        i = i + 2
     
    # If stack is empty
    # then return true
    if (len(s) == 0):
        return True
  
    return False;
 
# Driver code
if __name__=="__main__":
     
    N = 10
  
    # Given string
    s = "aeafacafae"
  
    if (isOddStringPalindrome(s, N)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by rutvik_56


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to check if String formed
// by odd indices is palindromic or not
static bool isOddStringPalindrome(String str,
                                  int n)
{
    int oddStringSize = n / 2;
 
    // Check if length of OddString
    // odd, to consider edge case
    bool lengthOdd = ((oddStringSize % 2 == 1) ?
                                true : false);
 
    Stack s = new Stack();
 
    int i = 1;
    int c = 0;
 
    // Push odd index character of
    // first half of str in stack
    while (i < n && c < oddStringSize / 2)
    {
        s.Push(str[i]);
        i += 2;
        c++;
    }
 
    // Middle element of odd length
    // palindromic String is not
    // compared
    if (lengthOdd)
        i = i + 2;
 
    while (i < n && s.Count > 0)
    {
        if (s.Peek() == str[i])
            s.Pop();
        else
            break;
        i = i + 2;
    }
 
    // If stack is empty
    // then return true
    if (s.Count == 0)
        return true;
 
    return false;
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 10;
 
    // Given String
    String s = "aeafacafae";
 
    if (isOddStringPalindrome(s, N))
        Console.Write("Yes\n");
    else
        Console.Write("No\n");
}
}
 
// This code is contributed by Princi Singh


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Functions checks if characters at
// odd index of the string forms
// palindrome or not
bool isOddStringPalindrome(string str,
                           int n)
{
 
    // Initialise two pointers
    int left, right;
 
    if (n % 2 == 0) {
        left = 1;
        right = n - 1;
    }
    else {
        left = 1;
        right = n - 2;
    }
 
    // Iterate till left <= right
    while (left < n && right >= 0
           && left < right) {
 
        // If there is a mismatch occurs
        // then return false
        if (str[left] != str[right])
            return false;
 
        // Increment and decrement the left
        // and right pointer by 2
        left += 2;
        right -= 2;
    }
 
    return true;
}
 
// Driver Code
int main()
{
    int n = 10;
 
    // Given String
    string s = "aeafacafae";
 
    // Function Call
    if (isOddStringPalindrome(s, n))
        cout << "Yes\n";
    else
        cout << "No\n";
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Functions checks if characters at
// odd index of the String forms
// palindrome or not
static boolean isOddStringPalindrome(String str,
                                     int n)
{
     
    // Initialise two pointers
    int left, right;
 
    if (n % 2 == 0)
    {
        left = 1;
        right = n - 1;
    }
    else
    {
        left = 1;
        right = n - 2;
    }
 
    // Iterate till left <= right
    while (left < n && right >= 0 &&
           left < right)
    {
         
        // If there is a mismatch occurs
        // then return false
        if (str.charAt(left) !=
            str.charAt(right))
            return false;
 
        // Increment and decrement the left
        // and right pointer by 2
        left += 2;
        right -= 2;
    }
     
    return true;
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 10;
 
    // Given String
    String s = "aeafacafae";
 
    // Function Call
    if (isOddStringPalindrome(s, n))
        System.out.print("Yes\n");
    else
        System.out.print("No\n");
}
}
 
// This code is contributed by Rohit_ranjan


Python3
# Python3 program for the above approach
 
# Functions checks if characters at
# odd index of the string forms
# palindrome or not
def isOddStringPalindrome(Str, n):
 
    # Initialise two pointers
    left, right = 0, 0
 
    if (n % 2 == 0):
        left = 1
        right = n - 1
    else:
        left = 1
        right = n - 2
 
    # Iterate till left <= right
    while (left < n and right >= 0 and
           left < right):
 
        # If there is a mismatch occurs
        # then return false
        if (Str[left] != Str[right]):
            return False
 
        # Increment and decrement the left
        # and right pointer by 2
        left += 2
        right -= 2
 
    return True
 
# Driver Code
if __name__ == '__main__':
     
    n = 10
 
    # Given string
    Str = "aeafacafae"
 
    # Function call
    if (isOddStringPalindrome(Str, n)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by himanshu77


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Functions checks if characters at
// odd index of the String forms
// palindrome or not
static bool isOddStringPalindrome(String str,
                                  int n)
{
     
    // Initialise two pointers
    int left, right;
 
    if (n % 2 == 0)
    {
        left = 1;
        right = n - 1;
    }
    else
    {
        left = 1;
        right = n - 2;
    }
 
    // Iterate till left <= right
    while (left < n && right >= 0 &&
           left < right)
    {
         
        // If there is a mismatch occurs
        // then return false
        if (str[left] !=
            str[right])
            return false;
 
        // Increment and decrement the left
        // and right pointer by 2
        left += 2;
        right -= 2;
    }
    return true;
}
 
// Driver Code
public static void Main(String[] args)
{
    int n = 10;
 
    // Given String
    String s = "aeafacafae";
 
    // Function Call
    if (isOddStringPalindrome(s, n))
        Console.Write("Yes\n");
    else
        Console.Write("No\n");
}
}
 
// This code is contributed by Rohit_ranjan


Javascript


输出:
Yes

时间复杂度: O(N)
空间复杂度: O(N)

高效的方法2:可以在不使用额外空间的情况下解决上述幼稚的方法。我们将使用双指针技术,左右分别从头和尾指向第一个奇数索引。以下是步骤:

  1. 检查字符串的长度是奇数还是偶数。
  2. 如果长度为奇数,则初始化 left = 1 和 right = N-2
  3. 否则,初始化 left = 1 和 right = N-1
  4. 将左指针增加 2 个位置,将右指针减少 2 个位置。
  5. 继续比较指针指向的字符,直到 left <= right。
  6. 如果没有发生不匹配,则该字符串是回文的,否则就不是回文的。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Functions checks if characters at
// odd index of the string forms
// palindrome or not
bool isOddStringPalindrome(string str,
                           int n)
{
 
    // Initialise two pointers
    int left, right;
 
    if (n % 2 == 0) {
        left = 1;
        right = n - 1;
    }
    else {
        left = 1;
        right = n - 2;
    }
 
    // Iterate till left <= right
    while (left < n && right >= 0
           && left < right) {
 
        // If there is a mismatch occurs
        // then return false
        if (str[left] != str[right])
            return false;
 
        // Increment and decrement the left
        // and right pointer by 2
        left += 2;
        right -= 2;
    }
 
    return true;
}
 
// Driver Code
int main()
{
    int n = 10;
 
    // Given String
    string s = "aeafacafae";
 
    // Function Call
    if (isOddStringPalindrome(s, n))
        cout << "Yes\n";
    else
        cout << "No\n";
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Functions checks if characters at
// odd index of the String forms
// palindrome or not
static boolean isOddStringPalindrome(String str,
                                     int n)
{
     
    // Initialise two pointers
    int left, right;
 
    if (n % 2 == 0)
    {
        left = 1;
        right = n - 1;
    }
    else
    {
        left = 1;
        right = n - 2;
    }
 
    // Iterate till left <= right
    while (left < n && right >= 0 &&
           left < right)
    {
         
        // If there is a mismatch occurs
        // then return false
        if (str.charAt(left) !=
            str.charAt(right))
            return false;
 
        // Increment and decrement the left
        // and right pointer by 2
        left += 2;
        right -= 2;
    }
     
    return true;
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 10;
 
    // Given String
    String s = "aeafacafae";
 
    // Function Call
    if (isOddStringPalindrome(s, n))
        System.out.print("Yes\n");
    else
        System.out.print("No\n");
}
}
 
// This code is contributed by Rohit_ranjan

蟒蛇3

# Python3 program for the above approach
 
# Functions checks if characters at
# odd index of the string forms
# palindrome or not
def isOddStringPalindrome(Str, n):
 
    # Initialise two pointers
    left, right = 0, 0
 
    if (n % 2 == 0):
        left = 1
        right = n - 1
    else:
        left = 1
        right = n - 2
 
    # Iterate till left <= right
    while (left < n and right >= 0 and
           left < right):
 
        # If there is a mismatch occurs
        # then return false
        if (Str[left] != Str[right]):
            return False
 
        # Increment and decrement the left
        # and right pointer by 2
        left += 2
        right -= 2
 
    return True
 
# Driver Code
if __name__ == '__main__':
     
    n = 10
 
    # Given string
    Str = "aeafacafae"
 
    # Function call
    if (isOddStringPalindrome(Str, n)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by himanshu77

C#

// C# program for the above approach
using System;
 
class GFG{
 
// Functions checks if characters at
// odd index of the String forms
// palindrome or not
static bool isOddStringPalindrome(String str,
                                  int n)
{
     
    // Initialise two pointers
    int left, right;
 
    if (n % 2 == 0)
    {
        left = 1;
        right = n - 1;
    }
    else
    {
        left = 1;
        right = n - 2;
    }
 
    // Iterate till left <= right
    while (left < n && right >= 0 &&
           left < right)
    {
         
        // If there is a mismatch occurs
        // then return false
        if (str[left] !=
            str[right])
            return false;
 
        // Increment and decrement the left
        // and right pointer by 2
        left += 2;
        right -= 2;
    }
    return true;
}
 
// Driver Code
public static void Main(String[] args)
{
    int n = 10;
 
    // Given String
    String s = "aeafacafae";
 
    // Function Call
    if (isOddStringPalindrome(s, n))
        Console.Write("Yes\n");
    else
        Console.Write("No\n");
}
}
 
// This code is contributed by Rohit_ranjan

Javascript


输出:
Yes

时间复杂度: O(N)
空间复杂度: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live