Editorial for Xâu đối xứng (Palindrom)


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.

Spoiler Alert


Approach 1

Tạo một xâu t là đảo ngược của xâu s.

isPalindrome(s) = true <=> s = t


Reference AC code | O(n) time | O(n) auxiliary space | string

C++
int main()
{
    string s;
    cin >> s;

    string t = s;
    reverse(t.begin(), t.end());

    cout << (s == t ? "YES" : "NO");    
}

Approach 2

Chạy i từ 1 -> n / 2, nếu vị trí đối xứng của i có giá trị khác nhau thì isPalindrome(s) = false


Reference AC code | O(n) time | O(1) auxiliary space | string

C++
int main()
{
    string s;
    cin >> s;

    for (int i = 0; i < s.size() / 2; ++i)
        if (s[i] != s[s.size() - i - 1])
            return cout << "NO", 0;

    cout << "YES";
    return 0;
}

Approach 3

Cho chạy 2 con trỏ (l từ đầu mảng -> cuối mảng) và (r từ cuối mảng -> đầu mảng).

Nệu tại lr tương ứng nhau có giá trị khác nhau thì isPalindrome(s) = false


Reference AC code | O(n) time | O(1) auxiliary space | string

C++
int main()
{
    string s;
    cin >> s;

    for (int l = 0, r = sz(s) - 1; l < r; l++, r--)
        if (s[l] != s[r])
            return cout << "NO", 0;

    cout << "YES";
    return 0;
}


Comments

There are no comments at the moment.