📜  TCS 编码练习题 |回文字符串

📅  最后修改于: 2021-10-23 07:46:34             🧑  作者: Mango

给定一个字符串,任务是使用命令行参数检查这个 String 是否是回文。

例子:

Input: str = "Geeks"
Output: No

Input: str = "GFG"
Output: Yes

方法:

  • 由于字符串是作为命令行参数输入的,因此不需要专用的输入行
  • 从命令行参数中提取输入字符串
  • 通过这个字符串的字符导线采用循环字符,直到刺痛的长度的一半
  • 检查字符从一端配以从另一端的字符
  • 如果任何字符不匹配,则该字符串不是回文
  • 如果所有字符匹配,则该字符串是回文

程序:

C
// C program to check if a string is Palindrome
// using command line arguments
  
#include 
#include 
#include 
  
// Function to reverse a string
int isPalindrome(char* str)
{
    int n = strlen(str);
    int i;
  
    // Check if the characters from one end
    // match with the characters
    // from the other end
    for (i = 0; i < n / 2; i++)
        if (str[i] != str[n - i - 1])
  
            // Since characters do not match
            // return 0 which resembles false
            return 0;
  
    // Since all characters match
    // return 1 which resembles true
    return 1;
}
  
// Driver code
int main(int argc, char* argv[])
{
  
    int res = 0;
  
    // Check if the length of args array is 1
    if (argc == 1)
        printf("No command line arguments found.\n");
  
    else {
  
        // Get the command line argument
        // and check if it is Palindrome
        res = isPalindrome(argv[1]);
  
        // Check if res is 0 or 1
        if (res == 0)
            // Print No
            printf("No\n");
        else
            // Print Yes
            printf("Yes\n");
    }
    return 0;
}


Java
// Java program to check if a string is Palindrome
// using command line arguments
  
class GFG {
  
    // Function to reverse a string
    public static int isPalindrome(String str)
    {
        int n = str.length();
  
        // Check if the characters from one end
        // match with the characters
        // from the other end
        for (int i = 0; i < n / 2; i++)
            if (str.charAt(i) != str.charAt(n - i - 1))
  
                // Since characters do not match
                // return 0 which resembles false
                return 0;
  
        // Since all characters match
        // return 1 which resembles true
        return 1;
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Check if length of args array is
        // greater than 0
        if (args.length > 0) {
  
            // Get the command line argument
            // and check if it is Palindrome
            int res = isPalindrome(args[0]);
  
            // Check if res is 0 or 1
            if (res == 0)
                // Print No
                System.out.println("No\n");
            else
                // Print Yes
                System.out.println("Yes\n");
        }
        else
            System.out.println("No command line "
                               + "arguments found.");
    }
}


输出:

  • 在 C 中:
  • 在Java:

想要从精选的视频和练习题中学习,请查看C 基础到高级C 基础课程