Skip to content

4030. Check ASCII Palindromic

Description

You are given a string s consisting of lowercase English letters.

Construct a binary string by replacing each character in s with the 8-bit binary representation of its ASCII value, including leading zeros, while preserving the original order of the characters.

Return true if the resulting binary string is a palindrome. Otherwise, return false.

Β 

Example 1:

Input: s = "ff"

Output: true

Explanation:

  • The ASCII value of f is 102, whose 8-bit binary representation is 01100110.
  • Thus, the binary string is 0110011001100110.
  • Since this binary string is a palindrome, the output is true.

Example 2:

Input: s = "leet"

Output: false

Explanation:

  • The ASCII values of l, e, e, and t are 108, 101, 101, and 116, respectively.
  • Their 8-bit binary representations are 01101100, 01100101, 01100101, and 01110100.
  • Thus, the binary string is 01101100011001010110010101110100.
  • Since this binary string is not a palindrome, the output is false.

Β 

Constraints:

  • 1 <= s.length <= 100
  • s consists of lowercase English letters.

Solutions

Solution 1: Simulation

Following the problem statement, we replace each character of \(s\) with the \(8\)-bit binary representation of its ASCII value (including leading zeros), concatenate them in order to obtain a binary string \(t\), and then check whether \(t\) is a palindrome.

The time complexity is \(O(n)\) and the space complexity is \(O(n)\), where \(n\) is the length of \(s\).

1
2
3
4
class Solution:
    def isPalindromic(self, s: str) -> bool:
        t = ''.join(format(ord(c), '08b') for c in s)
        return t == t[::-1]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    public boolean isPalindromic(String s) {
        StringBuilder t = new StringBuilder();
        for (char c : s.toCharArray()) {
            String b = Integer.toBinaryString(c);
            t.append("0".repeat(8 - b.length())).append(b);
        }
        return t.toString().equals(t.reverse().toString());
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
public:
    bool isPalindromic(string s) {
        string t;
        for (unsigned char c : s) {
            for (int i = 7; i >= 0; --i) {
                t += char('0' + ((c >> i) & 1));
            }
        }
        return ranges::equal(t, t | views::reverse);
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
func isPalindromic(s string) bool {
    var t []byte
    for _, c := range []byte(s) {
        for i := 7; i >= 0; i-- {
            t = append(t, '0'+((c>>i)&1))
        }
    }
    for i := range t[:len(t)/2] {
        if t[i] != t[len(t)-1-i] {
            return false
        }
    }
    return true
}
1
2
3
4
function isPalindromic(s: string): boolean {
    const t = [...s].map(c => c.charCodeAt(0).toString(2).padStart(8, '0')).join('');
    return t === [...t].reverse().join('');
}

Comments