题目描述:
首先第一步必须得将原序列化字符串按照","拆分成字符串数组。由于C++标准库没有自带的split函数,必须自己手写。直接搬用博客上的实现:http://www.cnblogs.com/lyf-sunicey/p/8489472.html
二、用STL进行字符串的分割
涉及到string类的两个函数find和substr:
1、find函数
原型:size_t find ( const string& str, size_t pos = 0 ) const;
功能:查找子字符串第一次出现的位置。
参数说明:str为子字符串,pos为初始查找位置。
返回值:找到的话返回第一次出现的位置,否则返回string::npos
2、substr函数
原型:string substr ( size_t pos = 0, size_t n = npos ) const;
功能:获得子字符串。
参数说明:pos为起始位置(默认为0),n为结束位置(默认为npos)
返回值:子字符串
实现如下:
//字符串分割函数
std::vector<std::string> split(std::string str,std::string pattern)
{
std::string::size_type pos;
std::vector<std::string> result;
str+=pattern;//扩展字符串以方便操作
int size=str.size();
for(int i=0; i<size; i++)
{
pos=str.find(pattern,i);
if(pos<size)
{
std::string s=str.substr(i,pos-i);
result.push_back(s);
i=pos+pattern.size()-1;
}
}
return result;
}
本题被归类于栈标签下,检测序列化是否是某棵树的前序遍历。
解决思路:
- 可以使用数学归纳法证明size是奇数
- 遇到数字就压栈
- 遇到‘#’就看栈顶元素是否也是‘#’号,如果栈顶不是‘#’压栈
- 如果栈顶是‘#’,则将子树用‘#’代替。首先弹栈一次,看栈是否为空,如果是,返回false,若果不是,看栈顶元素是否仍然是‘#’,如果是,返回false,否则再弹栈一次,最后压入‘#
- 最后根据栈中是否只剩下一个‘#’,如果是,则序列化是一棵树,否则返回false
代码如下:(c++)
class Solution {
public:
bool isValidSerialization(string preorder) {
vector<string> nodes = split(preorder, ",");
if (nodes.size() % 2 == 0)
return false;
deque<string> stack;
stack.push_back(nodes[0]);
for (int i =1; i < nodes.size(); i++) {
if (nodes[i] == "#") {
while(!stack.empty()&&stack.back() == "#") {
stack.pop_back();
if (stack.empty()||stack.back() == "#")
return false;
stack.pop_back();
}
}
stack.push_back(nodes[i]);
}
if (!stack.empty()&&stack.back()!="#") {
return false;
}
stack.pop_back();
if (stack.empty()) {
return true;
} else {
return false;
}
}
};
评论区的思路:
只要保证初度和入度相等即可,读一个不管是否为数字就应该-1,如果为数字就表示可以有两个孩子+2
public boolean isValidSerialization(String preorder) {
String[]temp = preorder.split(",");
if(temp[0].equals("#")&&temp.length==1) return true;
if(temp[0].equals("#")||temp.length%2==0) return false;
int count = 1;
for(int i =0;i<temp.length;i++)
{
count--;
if(count<0) return false;
if(!temp[i].equals("#"))
count+=2;
}
return count == 0;
}
还有一种直接根据叶节点数目比非叶节点多1,并且不到最后,res不能<=0
class Solution(object):
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
res = 1
for val in preorder.split(','):
if not res:
return False
if val == "#":
res -= 1
else:
res += 1
return not res
哎,我low了!