hihoCoder #1014 : Trie树
小白做题系列。
Code
//
// main.cpp
// Algorithm_OJ2
//
// Created by PTkin_Wang on 16/3/25.
// Copyright © 2016年 PTkin_Wang. All rights reserved.
//
#include <iostream>
#include <string.h>
using namespace std;
class Node {
public :
int count;
char letter;
bool exist_sub_node[26];
Node *sub_node[26];
Node() {
count = 0 ;
letter = '0';
memset(exist_sub_node, 0, 26);
memset(sub_node, 0, 26);
}
void insert(string str) {
++count;
if (0 == str.length())
return;
int index = str[0] - 'a';
if (!exist_sub_node[index]) { // not exist
Node *nextNode = new Node();
nextNode->letter = str[0];
exist_sub_node[index] = true;
sub_node[index] = nextNode;
}
sub_node[index]->insert(str.substr(1, str.size() - 1));
}
};
void check(string str, Node *node) {
if (0 == str.length()) {
cout << node->count;
return;
}
int index = str[0] - 'a';
if (!node->exist_sub_node[index]) {
cout << '0';
}
else {
check(str.substr(1, str.size() - 1), node->sub_node[index]);
}
}
int main(int argc, const char * argv[]) {
Node *root = new Node();
int input_num;
string input_word;
cin >> input_num; // number of words in the dictionary
for (int i = 0; i < input_num; ++i) {
cin >> input_word;
root->insert(input_word);
}
cin >> input_num; // number of words to be checked
for (int i = 0; i < input_num; ++i) {
cin >> input_word;
check(input_word, root);
if (i != input_num - 1)
cout << endl;
}
return 0;
}
Note
要得到 string
类型的长度应该使用 .size()
而不是 sizeof()
太久没写 C++ 都不熟悉了,误以为 sizeof(string)
可以得到字符串的长度,实际上如果要得到 string
的长度应该使用 string.size()
:)。
string
的本质是一个类,调用对象方法可以得到它的字符串长度,而使用 sizeof(string)
只能得到这个对象的大小,里面实际存储的包括了一个指向堆内的字符串的指针。
尝试一下下面代码:
#include <iostream>
using namespace std;
void output(string str) {
cout << "str = \"" << str << "\"" << endl
<< "sizeof(\"" << str << "\") = " << sizeof(str) << endl
<< "\"" << str << "\".size() = " << str.size() << "\n\n";
}
int main(int argc, const char * argv[]) {
string str1 = "ddd";
string str2 = "asudfghasodhsdf";
string str3 = "asudfghasodhfauosdfalsdfasudfgodhfauosdfa";
output(str1);
output(str2);
output(str3);
return 0;
}
将会输出
str = "ddd"
sizeof("ddd") = 24
"ddd".size() = 3
str = "asudfghasodhsdf"
sizeof("asudfghasodhsdf") = 24
"asudfghasodhsdf".size() = 15
str = "asudfghasodhfauosdfalsdfasudfgodhfauosdfa"
sizeof("asudfghasodhfauosdfalsdfasudfgodhfauosdfa") = 24
"asudfghasodhfauosdfalsdfasudfgodhfauosdfa".size() = 41