Algorithm to generate all combinations of a string

前端 未结 10 1949
日久生厌
日久生厌 2021-02-01 22:47

I found a link online that shows an algorithm to generate all combinations of a string: http://www.mytechinterviews.com/combinations-of-a-string

Algorithm is copied belo

10条回答
  •  南笙
    南笙 (楼主)
    2021-02-01 23:02

    import com.google.common.collect.Lists;
    
    import java.util.List;
    
    public class Combinations {
        public static String[] getCombinations(final String input) {
            final List combinations = Lists.newArrayList();
            getCombinations(input.toCharArray(), combinations, 0, "");
            return combinations.toArray(new String[0]);
        }
    
        private static void getCombinations(final char[] input, final List combinations, final int index, final String combination) {
            if (index == input.length) {
                combinations.add(combination);
                return;
            }
            getCombinations(input, combinations, index + 1, combination + String.valueOf(input[index]));
            getCombinations(input, combinations, index + 1, combination);
        }
    
    }
    

    Corresponding tests:

    import org.hamcrest.Matchers;
    import org.junit.Test;
    
    import static org.hamcrest.MatcherAssert.assertThat;
    
    public class CombinationsTest {
        @Test
        public void testCombinations() {
            verify(Combinations.getCombinations(""), "");
            verify(Combinations.getCombinations("a"), "a", "");
            verify(Combinations.getCombinations("ab"), "ab", "a", "b", "");
            verify(Combinations.getCombinations("abc"), "abc", "ab", "ac", "a", "bc", "b", "c", "");
            verify(Combinations.getCombinations("abcd"),
                    "abcd", "abc", "abd", "ab", "acd", "ac", "ad", "a", "bcd", "bc", "bd", "b", "cd", "c", "d", "");
        }
    
        private void verify(final String[] actual, final String... expected) {
            assertThat(actual, Matchers.equalTo(expected));
        }
    }
    

提交回复
热议问题