中级农民
- 积分
- 102
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2012-10-9
- 最后登录
- 1970-1-1
|
#include <iostream>.--
#include <string>
#include <vector>
using namespace std;
class TreeNode{.1point3acres
public:
TreeNode(string s, int l){
name = s;
level = l;
type = 0;
for(int i = 0; i < s.length(); i++){
if(s[i] == '.' && i != s.length() - 1) type = 1;
}
}
vector<TreeNode*> subDir;
vector<TreeNode*> file;
string name;
int type;
int level;
};. Χ
void addNode(TreeNode* dummy, TreeNode* temp){
if(dummy->level == temp->level - 1){. 1point 3acres
if(temp->type == 1) dummy->file.push_back(temp);
else dummy->subDir.push_back(temp);-baidu 1point3acres
}
else{
addNode(dummy->subDir.back(), temp);.google и
}
}
int helper(TreeNode* cur, string line){
// see if it is image file
int i = 0;. 1point3acres.com
for(; i < cur->name.length(); i++){
if(cur->name[i] == '.') break;
}
if(i < cur->name.length()){
string postfix = cur->name.substr(i + 1, cur->name.length() - i - 1);
if(postfix == "jpeg" || postfix == "gif" || postfix == "png"){// it is an image file
line = line + '/' + cur->name;
return line.length() - 1;
}
}
else if(i == cur->name.length() || i == cur->name.length() - 1){// it is a folder
line = line + '/' + cur->name;
int res = 0;
for(int j = 0; j < cur->subDir.size(); j++){
res = max(res, helper(cur->subDir[j], line));
}
for(int j = 0; j < cur->file.size(); j++){
res = max(res, helper(cur->file[j], line));
}
return res;
}
return 0;
}
int solution(string &S) {. Χ
// first split the string into substrings
if(S.empty()) return 0;
TreeNode* dummy = new TreeNode("", -1);
int prev = 0, counter = 0;
S += '\n';.--
while(counter < S.length()){
if(S[counter] != '\n') counter++;
else{
string cur = S.substr(prev, counter - prev);
prev = counter + 1;
int numOfSpaces = 0, level, i = 0;
for(; i < cur.length(); i++){-baidu 1point3acres
if(cur[i] != ' ') break;
numOfSpaces++;
}
cur = cur.substr(i, cur.length() - i);
level = numOfSpaces;. 1point 3acres
TreeNode* temp = new TreeNode(cur, level);. 1point 3 acres
addNode(dummy, temp);. .и
counter = prev;
}
}. 1point 3acres
string result;
return helper(dummy, result);. 1point3acres
}
其实并不难,但我最后时间不够,有一些bug没时间改了... |
|