Split a string to a string of valid words using Dynamic Programming

后端 未结 6 1195
不知归路
不知归路 2020-12-23 15:02

I need to find a dynamic programming algorithm to solve this problem. I tried but couldn\'t figure it out. Here is the problem:

You are given a string of n character

6条回答
  •  轮回少年
    2020-12-23 15:33

    Below is an O(n^2) solution for this problem.

    void findstringvalid() {
    string s = "itwasthebestoftimes";
    set dict;
    dict.insert("it");
    dict.insert("was");
    dict.insert("the");
    dict.insert("best");
    dict.insert("of");
    dict.insert("times");
    
    vector b(s.size() + 1, false);
    vector spacepos(s.size(), -1);
    //Initialization phase
    b[0] = true; //String of size 0 is always a valid string
    for (int i = 1; i <= s.size(); i++) {
        for (int j = 0; j ::iterator it = dict.find(temp);
                  if (it != dict.end()) {
                      b[i] = true;
                      spacepos[i-1] = j;
                  }
               }
            }
        }
    }
    if(b[s.size()])
        for (int i = 1; i < spacepos.size(); i++) {
            if (spacepos[i] != -1) {
                string temp = s.substr(spacepos[i], i - spacepos[i] + 1);
                cout << temp << " ";
        }
        }
    }
    

提交回复
热议问题