Permutations of capitalization

前端 未结 8 641
生来不讨喜
生来不讨喜 2020-12-21 01:24

I want to build a list containing every possible permutation of capitalization of a word. so it would be

List permutate(string word)
{
    List         


        
8条回答
  •  借酒劲吻你
    2020-12-21 01:45

    Assuming:

    1) You don't care too much that this is O(n*2^n)... although I'm curious to know: what is the best asymptotic run time for this type of problem?

    2) Your input is all lowercase.

    3) Your input is < 32 characters long. (# of usable bits in the permutation counter, i)

        List permutate(string word)
    {
        List ret = new List();
    
    // MAGIC HAPPENS HERE
    Dictionary toUppers = new Dictionary(26);
    toUppers.Add('a', 'A');
    toUppers.Add('b', 'B');
    toUppers.Add('c', 'C');
    toUppers.Add('d', 'D');
    toUppers.Add('e', 'E');
    toUppers.Add('f', 'F');
    toUppers.Add('g', 'G');
    toUppers.Add('h', 'H');
    toUppers.Add('i', 'I');
    toUppers.Add('j', 'J');
    toUppers.Add('k', 'K');
    toUppers.Add('l', 'L');
    toUppers.Add('m', 'M');
    toUppers.Add('n', 'N');
    toUppers.Add('o', 'O');
    toUppers.Add('p', 'P');
    toUppers.Add('q', 'Q');
    toUppers.Add('r', 'R');
    toUppers.Add('s', 'S');
    toUppers.Add('t', 'T');
    toUppers.Add('u', 'U');
    toUppers.Add('v', 'V');
    toUppers.Add('w', 'W');
    toUppers.Add('x', 'X');
    toUppers.Add('y', 'Y');
    toUppers.Add('z', 'Z');
    
    char[] wordChars = word.ToCharArray();
    int len = wordChars.Length;
    
    // iterate the number of permutations
    for(int i = 0; i < 2^len; i++) {
        char[] newWord = new char[len]();
    
        // apply "i" as a bitmask to each original char
        for(int n = 0; n < newWord.Length; n++) {
            if((1 << n) & i != 0) {
                newWord[n] = toUppers[wordChars[n]]; // or skip the dictionary and just call Char.ToUpper(wordChars[n])
            } else {
                newWord[n] = wordChars[n];
            }
        }
        ret.Add(new String(newWord));
    }
    
        return ret;
    }
    

    Note: I haven't compiled or tested this code. This is also implementing the bitwise compare that sharptooth suggested above.

提交回复
热议问题