Valid Question Mark Strings
MediumDynamic Programming · Paypal
You are given a string s made of lowercase English letters and ? characters. Every ? must be replaced by a lowercase letter (each ? independently; different ? may get the same letter).
A completed string is valid when both conditions hold:
- No two adjacent characters are equal.
- The first character equals the last character. (For a string of length 1 this is automatically true.)
Letters that are already in s cannot be changed. Return the number of different valid strings that can be produced. Because the answer can be very large, return it modulo 10^9 + 7. If no valid string can be produced, return 0.
Example 1
- Input:
- s = "a??a"
- Output:
- 600
- Explanation
- The ends are already equal. The first
?can be any letter excepta(25 choices); the second must differ from its left neighbour and from the finala(24 choices), giving 25 * 24 = 600.
Example 2
- Input:
- s = "?x?"
- Output:
- 25
- Explanation
- The first and last characters must be the same letter, and that letter must differ from
x, so there are 25 choices.
Example 3
- Input:
- s = "??"
- Output:
- 0
- Explanation
- The two characters must be equal (first and last) and different (adjacent) at the same time, which is impossible.
Constraints
1 <= s.length <= 2000sconsists of lowercase English letters and'?'