开发者

C++ Coding Logic - Various Ideas [closed]

开发者 https://www.devze.com 2023-01-05 19:45 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. 开发者_C百科 Closed 12 years ago.

I want to write a method to determine if a given string is a palindrome. E.g. "Madam I'm Adam", or "A man, a plan, a canal, Panama".

The prototype for the function is:

bool is_palindrome(char const * str)

I have a simple logic to check for equality by moving forward & backward from extreme ends of the string. But, i would like to know how many efficient ways to do this ? All ideas welcome from C++ gurus..


I don't think there is a much more efficient way, you do have to compare every character in the string.

Possible optimisations: You only have to check the first half of the string, and you can break out early as soon as you find a mismatch.

bool is_palindrome(char const * str) 
{
    size_t len = strlen(str);
    bool isPalindrome = false;    // It's debatable if a blank string is a palindrome or not

    for(int i = 0; i < len / 2; i++)
    {
        if(str[i] != str[len - i - 1])
        {
            isPalindrome = false;
            break;
        }
        isPalindrome = true;
    }

    return isPalindrome;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消