Permutations of capitalization

前端 未结 8 599
生来不讨喜
生来不讨喜 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 02:04

    To "permute" your string (technically, this isn't permutation since you're not changing the order of anything, but I don't want to be seen as an an*l-retentive :-), I would use a recursive approach, which basically "permutes" the string minus the first character and attaches those to the upper and lower variations of that character.

    Something like (in C, my C# is not really up to par so you'll have to convert it):

    #include <stdio.h>
    #include <string.h>
    
    static void permute (char *prefix, char *str) {
        char *newPrefix;
    
        /* End of string, print and return. */
    
        if (*str == '\0') {
            printf ("%s\n", prefix);
            return;
        }
    
        /* Allocate space for new prefix. */
    
        if ((newPrefix = malloc (strlen (prefix) + 2)) == NULL) {
            printf ("ERROR: Cannot allocate memory.\n");
            return;
        }
    
        /* Do lowercase/sole version and upper version if needed. */
    
        sprintf (newPrefix, "%s%c", prefix, *str);
        permute (newPrefix, &(str[1]));
    
        if (islower (*str) {
            sprintf (newPrefix, "%s%c", prefix, toupper(*str));
            permute (newPrefix, &(str[1]));
        }
    
        /* Free prefix and return. */
    
        free (newPrefix);
    }
    

     

    int main (int argc, char *argv[]) {
        char *str, *strPtr;
    
        /* Check and get arguments. */
    
        if (argc < 2) {
            printf ("Usage: permute <string to permute>\n");
            return 1;
        }
    
        if ((str = malloc (strlen (argv[1]) + 1)) == NULL) {
            printf ("ERROR: Cannot allocate memory.\n");
            return 1;
        }
        strcpy (str, argv[1]);
    
        /* Convert to lowercase. */
        for (strPtr = s; *strPtr != '\0'; strPtr++)
            *strPtr = toupper (*strPtr);
    
        /* Start recursion with empty prefix. */
    
        permute ("", str);
    
        /* Free and exit. */
    
        free (str);
        return 0;
    }
    

    Running this as "permute Pax1" returns:

    pax1
    paX1
    pAx1
    pAX1
    Pax1
    PaX1
    PAx1
    PAX1
    
    0 讨论(0)
  • 2020-12-21 02:06

    Use bitwise operations. For a word of length N you need an integer type represented by N bits. If the word is longer - split it. Iterate through values from 0 to 2N-1 and examine each bit from 0 to N-1. If the bit is 1 - upcase ( Char.ToUpper() ) the letter corresponding to that bit.

    This approach is better that a recursive algorithm since it is not prone to stack overflows on long words.

    0 讨论(0)
提交回复
热议问题