Блог пользователя angry_pikachu

Автор angry_pikachu, история, 2 года назад, По-английски

Source — Link

Given a string with lowercase letters and “?” where each “?” can be replaced by any lowercase character, find the total number of strings such that the first and last characters are the same and no adjacent characters are the same.

I am still new to DP, help would be appreciated

  • Проголосовать: нравится
  • +6
  • Проголосовать: не нравится

»
2 года назад, # |
  Проголосовать: нравится +5 Проголосовать: не нравится

You can iterate over every possible first character and calculate dp[i][j] — answer for prefix of length i with last character being j. It’s easy to get that dp[i][j] = sum of all dp[i — 1[k] for k != j. If you have s[i] = ‘?’, you calculate dp[i][j] for all j’s, otherwise only for j = s[i]. If you need to speed up your calculation time, you can notice that dp[i][j] = sum[i — 1] — dp[i — 1][j], where sum[i] is sum of dp[i][j] for all j’s. With all of that, you will get solution that works in O(n*26^2)