java - Return an array of strings containing all sub-sequences for s (except the empty string) ordered lexicographically? -


i need code (or snippet of code following problem or hint on how solve):

a sub sequence of string s obtained deleting 1 or more characters s. set of sub sequences string s = abc a, ab, ac, abc, b, bc, c, , empty string (which sub sequence of strings).

find possible sub sequences s , print them in lexicographic order.

this have come out it's not working:

treeset<string> ls = new treeset<>();      for(int i=0;i<s.length();i++)     {          for(int j=i;j<s.length();j++)         {             stringbuffer sb = new stringbuffer();              for(int k=i;k<j+1;k++)             {                 sb.append(s.charat(k));             }              ls.add(sb.tostring());         }      }         return ls.toarray(new string[ls.size()]); 

result:

testcase : abc 

output: ab abc b bc c

expected output: ab abc ac b bc c

your code looks substrings, consecutive sequences of characters original string. however, "ac" taken non-consecutive characters of input string, , you're not going output using approach.

one thing note input string has 3 characters, there 8 possible outputs (including empty string), , 23 = 8. should suggest want 8 possible combinations of 3 booleans, each boolean can true or false. each boolean correspond 1 character of input string, true means character input string in output, , false means isn't. generate 8 output strings looking @ possible true/false combinations. code them sorted using treeset appears working fine.

there few possible approaches:

(1) use array of boolean , find possible combinations. start false, change first 1 false true, change realization whenever change boolean true false, have change next boolean in array also. try doing on paper see how work.

(2) recognize array of boolean equivalent bits of integer, , can possible combinations of bits repeatedly adding 1 integer. you'd use bit operations figure out characters of input string include.

(3) recursion. if input string "abc", find subsequences of "bc" recursively. each subsequence s of "bc", s 1 subsequence of "abc", , "a" + s another.


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -