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