Back to course home
0% completed
Vote For New Content
Easy to understand C# solution with Recursive DFS
Debasis B
Feb 2, 2025
List<string> result = new List<string>(); public List<string> generateGeneralizedAbbreviation(string word) { // Begin process generate(word, 0, new List<char>()); // coalesce contiguous spaces to count of spaces processResult(); return result; } private void processResult() { for (int i = 0; i < result.Count; i++) { result[i] = processResult(result[i]); } } private string processResult(string result) { Stack<char> chars = new Stack<char>(); for (int i = 0; i < result.Length; i++) { if (result[i] == ' ') { // if top is digit: pop, increment and put back otherwise push 1 if (chars.TryPeek(out char top) && char.IsDigit(top)) { chars.Push((char)(chars.Pop() + 1)); } else { chars.Push('1'); } } else { chars.Push(result[i]); } } string s = string.Empty; while (chars.TryPop(out char item)) { s = $"{item}{s}"; } return s; } private void generate(string word, int index, List<char> list) { // Base case: index out of bound, add to result if (index == word.Length) { result.Add(string.Concat(list)); return; } // Take character at index and recursively generate with next character list.Add(word[index]); generate(word, index + 1, list); // Backtrack: undo taking character list.RemoveAt(list.Count - 1); // Take space and recursively generate with next character list.Add(' '); generate(word, index + 1, list); // Backtrack: undo taking space list.RemoveAt(list.Count - 1); }
0
0
Comments
Comments