[LeetCode] The Wording Game

2868. The Wording Game

Alice and Bob each have a lexicographically sorted array of strings named a and b respectively.

They are playing a wording game with the following rules:

  • On each turn, the current player should play a word from their list such that the new word is closely greater than the last played word; then it’s the other player’s turn.
  • If a player can’t play a word on their turn, they lose.

Alice starts the game by playing her lexicographically smallest word.

Given a and b, return true if Alice can win knowing that both players play their best, and false otherwise.

A word w is closely greater than a word z if the following conditions are met:

  • w is lexicographically greater than z.
  • If w1 is the first letter of w and z1 is the first letter of z, w1 should either be equal to z1 or be the letter after z1 in the alphabet.
  • For example, the word "care" is closely greater than "book" and "car", but is not closely greater than "ant" or "cook".

A string s is lexicographically greater than a string t if in the first position where s and t differ, string s has a letter that appears later in the alphabet than the corresponding letter in t. If the first min(s.length, t.length) characters do not differ, then the longer string is the lexicographically greater one.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
bool canAliceWin(vector<string>& a, vector<string>& b) {
int i = 0, j = 0;
while(i < a.size()) {
while(j < b.size() and b[j] <= a[i]) j += 1;
if(j == b.size() or b[j][0] > a[i][0] + 1) return true;
while(i < a.size() and a[i] <= b[j]) i += 1;
if(i == a.size() or a[i][0] > b[j][0] + 1) return false;
}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/10/09/PS/LeetCode/the-wording-game/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.