Find the number of occurrences of a subsequence in a string

前端 未结 9 1574
粉色の甜心
粉色の甜心 2020-12-04 05:13

For example, let the string be the first 10 digits of pi, 3141592653, and the subsequence be 123. Note that the sequence occurs twice:



        
9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 05:46

    psh. O(n) solutions are way better.

    Think of it by building a tree:

    iterate along the string if the character is '1', add a node to the the root of the tree. if the character is '2', add a child to each first level node. if the character is '3', add a child to each second level node.

    return the number of third layer nodes.

    this would be space inefficient so why don't we just store the number of nodes a each depth:

    infile >> in;
    long results[3] = {0};
    for(int i = 0; i < in.length(); ++i) {
        switch(in[i]) {
            case '1':
            results[0]++;
            break;
            case '2':
            results[1]+=results[0];
            break;
            case '3':
            results[2]+=results[1];
            break;
            default:;
        }
    }
    
    cout << results[2] << endl;
    

提交回复
热议问题