Algorithm to generate all combinations of a string

前端 未结 10 1935
日久生厌
日久生厌 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:13

    We can generate all the sub strings of a string by using the bit concept which has been mentioned previously. Here is the code (in C++ , but you get the idea) to do that : -

    string s;
    int n = s.size();
    int num = 1<

    Eg;- String s = abc ,

     The size is 3  . So we check from 1 to 7 ( 1<<3).
     for i = 1 ( 001 ) , the first bit is set, so a is printed.
     for i = 2 ( 010 ) , the second bit is set, so b is printed.
     for i = 3 ( 011 ) , the first and second bit are set, so ab is printed.
     .
     .
     .
     for i = 7 ( 111 ) , all three bits are set, so abc is printed.
    

提交回复
热议问题