← 返回 walmartlabs 的题目列表Insert Spaces Around Palindrome Layers
类型:qbank
Given a palindrome string, split it into nested mirror layers and join them with single spaces, separating the symmetric outer characters from the innermost asymmetric core.
Requirements
Input: s: String — a palindrome (the round did not specify behavior for non-palindromes; clarify with the interviewer).
Repeatedly peel matching characters from the two ends while they are equal, emitting each peeled character as its own token. The remaining middle slice — the first place where s[i] != s[n-1-i] or the lone middle character — is emitted as a single token.
Join all tokens with a single space.
Examples
Input: "abcxyba"
Output: "a b cxy b a"
→ peel 'a' / 'a' (match), peel 'b' / 'b' (match), 'c'!='y' → middle "cxy".
Input: "aba"
Output: "a b a"
→ peel 'a' / 'a', single middle 'b'.
Input: "abba"
Output: "a b b a" if every char is its own token, or "a bb a" if the matched pair is emitted as one token — surface this ambiguity with the interviewer.
Notes
The intended algorithm is a two-pointer walk from both ends. At each step, compare s[left] and s[right]. If they match, emit s[left] as a left token and s[right] as a right token (the round implied per-character emission for the matched layers) and move both pointers inward. If they differ, emit s[left..right] inclusive as a single middle token and stop.
After the loop, if left == right, emit s[left] as the lone middle token. If left > right, emit no middle token.
The collected tokens are: left-tokens in encounter order, then the middle token (if any), then right-tokens in reverse encounter order. Join with a single space.
Confirm two ambiguities with the interviewer: (1) whether equal layers should be batched ("aa" → "aa" or "a a"); (2) what to do when the input is not a palindrome — emit the whole string as one token, or report an error.
Preparation
Code the two-pointer scan with an explicit left, right, List<String> leftTokens, List<String> rightTokens, String middle = null. The structural separation makes the join trivial and avoids index gymnastics.
Run it against the three boundary cases above before the interviewer asks: even-length palindrome, odd-length palindrome, and a palindrome with an asymmetric inner span ("abcxyba").
If the interviewer drops the palindrome guarantee, switch to a longest-mirrored-prefix scan: peel only while characters match, and emit the unmatched middle slice as a single token.