Hướng dẫn find all non overlapping substrings python - tìm tất cả các chuỗi con không chồng chéo python

Đưa ra một chuỗi, tìm tất cả các kết hợp của các chuỗi con không chồng chéo của nó.

Xin lưu ý rằng vấn đề cụ thể nhắm mục tiêu các chuỗi con tiếp giáp (nghĩa là, chiếm các vị trí liên tiếp) và vốn đã duy trì thứ tự của các yếu tố.

& nbsp; Ví dụ,
For example,

Đầu vào: & nbsp; ABC ABC

& nbsp; Đầu ra: [a, b, c], [a, bc], [ab, c], [abc]Output: [A, B, C], [A, BC], [AB, C], [ABC]

 

& nbsp; Đầu vào: & nbsp; A B C DInput:  ABCD

& nbsp; Đầu ra: [a, b, c, d], [a, b, cd], [a, bc, d], [a, bcd], [ab, c, d], [ab, cd], [abc , D], [ABCD]Output: [A, B, C, D], [A, B, CD], [A, BC, D], [A, BCD], [AB, C, D], [AB, CD], [ABC, D], [ABCD]

Thực hành vấn đề này

Ý tưởng là sử dụng đệ quy để giải quyết vấn đề này. Đối với một chuỗi đã cho str có độ dài n, hãy xem xét mỗi tiền tố str[0, i] của từng người một. Chúng tôi nối các tiền tố vào chuỗi đầu ra bằng cách đặt nó trong dấu ngoặc đơn và tái diễn cho chuỗi con còn lại str[i+1, n-1]. Nếu mọi chuỗi con của chuỗi ban đầu được xử lý, hãy thêm chuỗi đầu ra vào kết quả.

Sau đây là việc thực hiện C ++, Java và Python của ý tưởng:

C++


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

#bao gồm

#bao gồm

#bao gồm

#bao gồm

usingnamespacestd;namespace std;

// Tìm tất cả các kết hợp của các chuỗi con không chồng chéo của một chuỗi đã cho

voidfindCombinations(stringstr,vector&substring,findCombinations(string str,vector<string>&substring,

        set&combinations)set<vector<string>>&combinations)

{

& nbsp; & nbsp; & nbsp; & nbsp; // Nếu tất cả các ký tự của chuỗi đầu vào được xử lý,// if all characters of the input string are processed,

& nbsp; & nbsp; & nbsp; & nbsp; // Thêm chuỗi đầu ra để kết quả// add the output string to result

    if(str.length()==0)if (str.length()==0)

    {{

        vectoroutput(substring);vector<string> output(substring);

        combinations.insert(output);combinations.insert(output);

        return;return;

    }}

& nbsp; & nbsp; & nbsp; & nbsp; // nối mỗi tiền tố `str [0, i]` vào chuỗi đầu ra và tái diễn cho// append each prefix `str[0, i]` to the output string and recur for

& nbsp; & nbsp; & nbsp; & nbsp;// remaining substring `str[i+1, n-1]`

    for(inti=0;ifor (inti=0;i<str.length();i++)

    {{

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;// push prefix `str[0, i]` into the output vector

        substring.push_back(str.substr(0,i+1));substring.push_back(str.substr(0,i +1));

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;// recur for the remaining string `str[i+1, n-1]`

        findCombinations(str.substr(i+1),substring,combinations);findCombinations(str.substr(i+ 1),substring,combinations);

& nbsp; & nbsp; & nbsp; & nbsp;// backtrack: remove current substring from the output vector

        substring.pop_back();substring.pop_back();

    }}

}

setfindCombinations(strings)<vector<string>>findCombinations(string s)

{

    setcombinations;set<vector<string>> combinations;

& nbsp; & nbsp; & nbsp; & nbsp; // Nếu tất cả các ký tự của chuỗi đầu vào được xử lý,// base case

    if(s.length()==0){if (s.length()==0){

        returncombinations;returncombinations;

    }}

& nbsp; & nbsp; & nbsp; & nbsp; // Thêm chuỗi đầu ra để kết quả// vector to store non-overlapping substrings

    vectorsubstring;vector<string>substring;

& nbsp; & nbsp; & nbsp; & nbsp; // nối mỗi tiền tố `str [0, i]` vào chuỗi đầu ra và tái diễn cho// find all non-overlapping substrings

    findCombinations(s,substring,combinations);findCombinations(s,substring,combinations);

    returncombinations;returncombinations;

}

& nbsp; & nbsp; & nbsp; & nbsp; // trường hợp cơ sở

voidprintVector(vectorconst&out) printVector(vector<string>const&out)

{

& nbsp; & nbsp; & nbsp; & nbsp; // Nếu tất cả các ký tự của chuỗi đầu vào được xử lý,for(auto str:out){

        coutcout<<str<<" ";

    }}

    coutcout<<endl;

}

intmain()main()

{

& nbsp; & nbsp; & nbsp; & nbsp; // Nếu tất cả các ký tự của chuỗi đầu vào được xử lý,// input string

    stringstr="ABCD";string str="ABCD";

& nbsp; & nbsp; & nbsp; & nbsp; // nối mỗi tiền tố `str [0, i]` vào chuỗi đầu ra và tái diễn cho// find all non-overlapping substrings

    setcombinations=findCombinations(str);set<vector<string>>combinations= findCombinations(str);

    for(vectorcombination:combinations){for(vector<string>combination:combinations){

        printVector(combination);printVector(combination);

    }}

    return0;return 0;

}

& nbsp; & nbsp; & nbsp; & nbsp; // trường hợp cơ sở

& nbsp; & nbsp; & nbsp; & nbsp; // vector để lưu trữ các chuỗi con không chồng chéo

A B C D
A B CD
A BC D
A BCD
AB C D
AB CD
ABC D
ABCD

& nbsp; & nbsp; & nbsp; & nbsp; // tìm tất cả các chuỗi con không chồng chéo


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

importjava.util.*;java.util.*;

// Chức năng tiện ích để in nội dung của vectơclass Main

{

& nbsp; & nbsp; & nbsp; & nbsp; // Nếu tất cả các ký tự của chuỗi đầu vào được xử lý,// Find all combinations of non-overlapping substrings of a given string

    publicstaticvoidfindCombinations(Stringstr,Dequesubstring,publicstatic voidfindCombinations(Stringstr,Deque substring,

                                        Setcombinations)Set<List>combinations)

    {{

& nbsp; & nbsp; & nbsp; & nbsp; // Thêm chuỗi đầu ra để kết quả// if all characters of the input string are processed,

& nbsp; & nbsp; & nbsp; & nbsp; // nối mỗi tiền tố `str [0, i]` vào chuỗi đầu ra và tái diễn cho// add the output string to result

        if(str.length()==0){if (str.length()==0){

            combinations.add(newArrayList(substring));combinations.add(newArrayList<>(substring));

            return;return;

        }}

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp;// add each substring `str[0, i]` to the output string and recur for

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;// remaining substring `str[i+1, n-1]`

        for(inti=0;ifor(inti=0; i<str.length(); i++)

        {{

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;// push substring `str[0, i]` into the output string

            substring.addLast(str.substring(0,i+1));substring.addLast(str.substring(0,i +1));

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;// recur for the remaining string `str[i+1, n-1]`

            findCombinations(str.substring(i+1),substring,combinations);findCombinations(str.substring(i+ 1),substring,combinations);

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;// backtrack: remove current substring from the output

            substring.pollLast();substring.pollLast();

        }}

    }}

    publicstaticSetfindCombinations(Strings)publicstaticSet<List>findCombinations(Strings)

    {{

        Setcombinations=newHashSet();Set<List>combinations =newHashSet<>();

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; // case// base case

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;if(s==null|| s.length()==0){

            returncombinations;returncombinations;

        }}

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; // Chuỗi// string to store non-overlapping substrings

        Dequesubstring=newArrayDeque();Dequesubstring=newArrayDeque<>();

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbs// find all non-overlapping substrings

        findCombinations(s,substring,combinations);findCombinations(s,substring,combinations);

        returncombinations;returncombinations;

    }}

    publicstaticvoidmain(String[]args)publicstatic voidmain(String[]args)

    {{

& nbsp;// input string

        Stringstr="ABCD";Stringstr="ABCD";

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbs// find all non-overlapping substrings

        Setcombinations=findCombinations(str);Set<List> combinations=findCombinations(str);

        System.out.println(combinations);System.out.println(combinations);

    }}

& nbsp;

}

Tải xuống & nbsp; & nbsp; mã

[[AB, CD], [A, BC, D], [A, BCD], [ABC, D], [A, B, CD], [AB, C, D], [A, B, C, D], [ABCD]]

Đầu ra: [[ab, cd], [a, bc, d], [a, bcd], [abc, d], [a, b, cd], [ab, c, d], [a, b, C, D], [ABCD]]


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

Python

deffindCombinations(s,combinations,substring=[]):findCombinations(s,combinations, substring=[]):

# Tìm tất cả các kết hợp của các chuỗi con không chồng chéo của một chuỗi đã cho# if all characters of the input are processed,

& nbsp; & nbsp; & nbsp; & nbsp;# nếu tất cả các ký tự của đầu vào được xử lý,# add the output string to result

    ifnots:ifnots:

& nbsp; & nbsp; & nbsp; & nbsp;# Thêm chuỗi đầu ra vào kết quả# output string to store non-overlapping substrings

        combinations.add(tuple(substring))combinations.add(tuple(substring))

        returnreturn

& nbsp; & nbsp;# add each substring `s[0, i]` to the output string and recur for

& nbsp; & nbsp; & nbsp; & nbsp;# Thêm mỗi chuỗi con [0, i] `vào chuỗi đầu ra và tái diễn# remaining substring `s[i+1, n-1]`

    foriinrange(len(s)):fori inrange(len(s)):

& nbsp; & nbsp; & nbsp; & nbsp;## push substring `s[0, i]` into the output string

        substring.append(s[:i+1])substring.append(s[:i +1])

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;# push# recur for the remaining string `s[i+1, n-1]`

        findCombinations(s[i+1:],combinations,substring)findCombinations(s[i+1:], combinations,substring)

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;# backtrack: remove current substring from the output

        substring.pop()substring.pop()

deffindAllCombinations(s):findAllCombinations(s):

& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;# base case

    ifnots:ifnots:

        returnset()returnset()

& nbsp; & nbsp; & nbsp; & nbsp;# Case cơ sở# find all non-overlapping substrings

    combinations=set()combinations =set()

    findCombinations(s,combinations)findCombinations(s, combinations)

    returncombinationsreturncombinations

if__name__=='__main__':__name__ =='__main__':

& nbsp; & nbsp; & nbsp; & nbsp;# chuỗi đầu vào# input string

    s='ABCD's= 'ABCD'

& nbsp; & nbsp; & nbsp; & nbsp;# Tìm tất cả các chuỗi con không chồng chéo# find all non-overlapping substrings

    combinations=findAllCombinations(s)combinations= findAllCombinations(s)

    print(combinations)print(combinations)

Tải xuống & nbsp; & nbsp; mã

Đầu ra: {('ab', 'cd'), ('a', 'bcd'), ('a', 'bc', 'd'), ('abc', 'd'), ('ab',' C ',' d '), (' abcd ',), (' a ',' b ',' c ',' d '), (' a ',' b ',' cd ')}

{(‘AB’, ‘CD’), (‘A’, ‘BCD’), (‘A’, ‘BC’, ‘D’), (‘ABC’, ‘D’), (‘AB’, ‘C’, ‘D’), (‘ABCD’,), (‘A’, ‘B’, ‘C’, ‘D’), (‘A’, ‘B’, ‘CD’)}

Độ phức tạp của thời gian của giải pháp trên là theo cấp số nhân vì có chính xác các kết hợp 2n-1, trong đó n là độ dài của chuỗi đầu vào.

Cảm ơn vì đã đọc.

Vui lòng sử dụng trình biên dịch trực tuyến của chúng tôi để đăng mã trong các nhận xét bằng C, C ++, Java, Python, JavaScript, C#, PHP và nhiều ngôn ngữ lập trình phổ biến hơn.

Như chúng tôi?Giới thiệu chúng tôi với bạn bè của bạn và giúp chúng tôi phát triển.Mã hóa hạnh phúc :) :)