Letter Case Permutation, by LeetCode

A relatively easy problem, by LeetCode: https://leetcode.com/problems/letter-case-permutation/description/:

Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string.  Return a list of all possible strings we could create.
Examples:
Input: S = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]

Input: S = "3z4"
Output: ["3z4", "3Z4"]

Input: S = "12345"
Output: ["12345"]

Given that Len(S)<=12, a simple recursive solution will do it. I usually use the same recipe for such a problem:

  • I usually prefer to have an internal method which does the actual processing,  doesn't return anything, and passes the "return value" by reference
  • There is a string which is the "current" working string. This will be the candidate to be added to the retVal
  • The recursion is controlled based on the position (index) being worked on right now. When it goes past (or equal, sure..) the length of S, stop
  • Call recursively for the current index irrespective of the character being processed
  • Then deal with the cases for either lower or upper case. Swap them appropriately
That should do it. Code is below, cheers, Marcelo


public class Solution

{
public IList<string> LetterCasePermutation(string S)
{
IList<string> retVal = new List<string>();
LetterCasePermutationInternal("", 0, S, ref retVal);
return retVal;
}

private void LetterCasePermutationInternal(string current, int pos, string S, ref IList<string> retVal)
{
if (pos == S.Length)
{
retVal.Add(current);
return;
}
LetterCasePermutationInternal(current + S[pos].ToString(), pos + 1, S, ref retVal);
if (S[pos] >= 'a' && S[pos] <= 'z')
{
LetterCasePermutationInternal(current + S[pos].ToString().ToUpper(), pos + 1, S, ref retVal);
}
else if (S[pos] >= 'A' && S[pos] <= 'Z')
{
LetterCasePermutationInternal(current + S[pos].ToString().ToLower(), pos + 1, S, ref retVal);
}
}
}

Comments

  1. nicely done! Python version is a bit shorter (1 liner) :)

    class Solution:
    def letterCasePermutation(self, S):
    return [head + permutation for head in ((S[0].lower(), S[0].upper()) if S[0].isalpha() else S[0]) for permutation in self.letterCasePermutation(S[1:])] if S else [""]

    Or for fans of Haskell naming style:

    return [x + xs for x in ((S[0].lower(), S[0].upper()) if S[0].isalpha() else S[0]) for xs in self.letterCasePermutation(S[1:])] if S else [""]

    Cheers,
    Taras

    ReplyDelete

Post a Comment

Popular posts from this blog

Changing the root of a binary tree

ProjectEuler Problem 719 (some hints, but no spoilers)

The Power Sum, a recursive problem by HackerRank