Chat app~25 min2s · 256 MBtarget O(n²) time, O(n) spaceclassic twin: lc-647dp
A chat app has a word game. When a player types a word, the app counts its palindromic pieces. These are the parts of the word, made of letters next to each other, that read the same forwards and backwards.
A piece is identified by where it starts and ends. If the same letters appear twice in different places, they count as two pieces. A single letter is a piece too.
Write count_palindromic_pieces(text).
text is the typed word, lowercase letters.i to position j, with i ≤ j.Input: text = "abcba"
Output: 7Let pal[i][j] say whether the piece from i to j reads the same backwards. A piece is a palindrome when its end letters match and the piece inside it is a palindrome. A piece of one or two letters has no piece inside, so matching ends are enough. Fill the rows from the last start to the first, because a row reads the row below it.
| start \ end | 0 (a) | 1 (b) | 2 (c) | 3 (b) | 4 (a) |
|---|---|---|---|---|---|
| 4 (a) | yes | ||||
| 3 (b) | yes | no | |||
| 2 (c) | yes | no | no | ||
| 1 (b) | yes | no | yes | no | |
| 0 (a) | yes | no | no | no | yes |
The five single letters are palindromes, and so are bcb and abcba: 7 pieces.
Input: text = "abc"
Output: 3Only the three single letters are palindromes.
Input: text = "aaa"
Output: 6The pieces are a three times, aa twice and aaa once. Equal pieces in different places count separately.
1 ≤ len(text) ≤ 1000text contains lowercase letters onlyA word of 1,000 letters has 1,000 × 1,001 / 2 = 500,500 pieces. Checking each from both ends is up to 83,458,250 letter comparisons in the worst case. A table with one entry for each piece costs about half a million small steps.