Let's say you have a phrase without any spaces - eg. "thisisawesome". Given a dictionary, how would you add spaces in this string?
-----------------------------------------------------------------------------
Use Trie
//matchLongest return the first character that can’t match
class Solution {
public:
bool addSpace(const string& s, vector<string> res, Trie* root) {
int i, j, pos = matchLongest(root, s), len = s.length();
if (len == pos)
return true;
else {
for (i = pos; i > 0; --i) {
res.push_back(s.substr(0,i));
if (addSpace(s.substr(i+1), res, root))
return true;
res.pop_back();
}
return false;
}
}
}
However, above code isn't right, here's the result:
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <string>
#define base 'a'
#define sonnum 26
using namespace std;
class Trie {
public:
bool terminal;
Trie *child[sonnum];
Trie(bool t = false):terminal(t) {
for (int i = 0; i < sonnum; ++i)
child[i] = NULL;
}
};
Trie* build() {
Trie* res = new Trie(false);
return res;
}
void insert(const string& s, Trie* root) {
int i, len = s.length();
for (i = 0; i < len; ++i) {
if (root->child[s[i]-base] == NULL)
root->child[s[i]-base] = new Trie();
root = root->child[s[i]-base];
}
root->terminal = true;
}
class Solution {
public:
vector<int> find(const string& s, Trie* root) {
vector<int> res;
int i, len = s.length();
for (i = 0; i < len; ++i) {
if (root->child[s[i]-base]) {
root = root->child[s[i]-base];
if (root->terminal)
res.push_back(i);
}
else
break;
}
return res;
}
bool addSpace(const string& s, vector<string>& res, Trie* root) {
vector<int> pos = find(s, root);
int i, size = pos.size(), len = s.length();
for (i = size - 1; i >= 0; --i) {
res.push_back(s.substr(0, pos[i]+1));
if (pos[i] == len-1)
return true;
if (addSpace(s.substr(pos[i]+1), res, root))
return true;
res.pop_back();
}
return false;
}
};
int main() {
Solution s;
string str[] = {"da", "m", "mam", "am", "ample", "pleased", "ease", "lease", "leased", "ad"};
Trie *root = build();
int size = sizeof(str)/sizeof(str[0]);
vector<string> res;
string ss = "mampleasedadda";
for (int i = 0; i < size; ++i) {
insert(str[i], root);
}
if (s.addSpace(ss, res, root)) {
for (int i = 0; i < res.size(); ++i)
cout << res[i] << " ";
cout << endl;
}
return 0;
}