1132. Before and After Puzzle

  • Difficulty: Medium

  • Topics: String

  • Similar Questions:

Problem:

Given a list of phrases, generate a list of Before and After puzzles.

A phrase is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a phrase.

Before and After puzzles are phrases that are formed by merging two phrases where the last word of the first phrase is the same as the first word of the second phrase.

Return the Before and After puzzles that can be formed by every two phrases phrases[i] and phrases[j] where i != j. Note that the order of matching two phrases matters, we want to consider both orders.

You should return a list of distinct strings sorted lexicographically.

 

Example 1:

Input: phrases = ["writing code","code rocks"]
Output: ["writing code rocks"]

Example 2:

Input: phrases = ["mission statement",
                  "a quick bite to eat",
                  "a chip off the old block",
                  "chocolate bar",
                  "mission impossible",
                  "a man on a mission",
                  "block party",
                  "eat my words",
                  "bar of soap"]
Output: ["a chip off the old block party",
         "a man on a mission impossible",
         "a man on a mission statement",
         "a quick bite to eat my words",
         "chocolate bar of soap"]

Example 3:

Input: phrases = ["a","b","a"]
Output: ["a"]

 

Constraints:

  • 1 <= phrases.length <= 100
  • 1 <= phrases[i].length <= 100

Solutions:

class Solution {
public:
    vector<string> beforeAndAfterPuzzles(vector<string>& phrases) {
        unordered_map<string, vector<int>> firstWordToPhase;

        for (int i = 0; i < phrases.size(); ++i) {
            string firstWord = getFirstWord(phrases[i]);
            firstWordToPhase[firstWord].push_back(i);
        }

        set<string> ret;
        for (int i = 0; i < phrases.size(); ++i) {
            int lastWordIndex = getLastWordIndex(phrases[i]);
            string lastWord = phrases[i].substr(lastWordIndex);
            if (firstWordToPhase.count(lastWord) > 0) {
                string prefix = phrases[i].substr(0, lastWordIndex);
                for (auto& j : firstWordToPhase[lastWord]) {
                    if (j == i) continue;
                    ret.insert(prefix + phrases[j]);
                }
            }
        }

        return {ret.begin(), ret.end()};
    }

private:
    string getFirstWord(const string& str) {
        int pos = 0;
        while (pos < str.length() && str[pos] != ' ') {
            ++pos;
        }

        return str.substr(0, pos);
    }

    int getLastWordIndex(const string& str) {
        int pos = str.length() - 1;
        while (pos >= 0 && str[pos] != ' ') {
            --pos;
        }

        return pos + 1;
    }

};

results matching ""

    No results matching ""