Skip to content

Instantly share code, notes, and snippets.

@fwrq41251
Last active October 31, 2016 02:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fwrq41251/1db0d461288e66215ea5c71fd7571534 to your computer and use it in GitHub Desktop.
Save fwrq41251/1db0d461288e66215ea5c71fd7571534 to your computer and use it in GitHub Desktop.
leetcode.
import scala.collection.mutable.ListBuffer
/**
* Created by User on 10/28/2016.
*/
object LongestAbsoluteFilePath {
class Node(val name: String, val depth: Int) {
val nodeType: NodeType.Value = getNodeType(name)
val subNodes = new ListBuffer[Node]
def addNode(node: Node) = subNodes += node
def addNodes(nodes: List[Node]) = subNodes.appendAll(nodes)
override def toString = s"Node(nodeType=$nodeType, name=$name, depth=$depth)"
}
object NodeType extends Enumeration {
val File, Dir = Value
}
def parse(input: String): Option[Node] = {
val strs = input.split("\n")
if (strs.isEmpty) {
Option.empty
}
else {
val headName = strs.head
var depth = 0
val root = new Node(headName, depth)
val tail = strs.tail
if (tail.isEmpty) {
Option(root)
}
else {
val stack = new java.util.Stack[Node]()
stack.push(root)
for (nodeStr <- tail) {
val node = getNode(nodeStr)
val parent = if (node.depth > depth) {
stack.peek()
}
else {
while (stack.peek().depth != node.depth - 1) {
stack.pop()
}
stack.peek()
}
parent.addNode(node)
stack.push(node)
depth = node.depth
}
Option(root)
}
}
}
/**
*
* @param nodeStr
* @return depth -> nodeName
*/
def getNode(nodeStr: String): Node = {
var tabCount = 0
var tail = nodeStr
while (tail.contains("\t")) {
tabCount += 1
tail = tail.substring(1)
}
new Node(tail, tabCount)
}
def getLongestLength(input: String): Int = {
parse(input) match {
case Some(node) => 2
case None => 0
}
}
def getNodeType(name: String): NodeType.Value = {
if (name.contains('.')) NodeType.File else NodeType.Dir
}
def main(args: Array[String]): Unit = {
val input = "dir\n\tsubdir1\n\t\tsubsubdir1\n\t\t\tfile1.ext\n\tsubdir2\n\tsubdir3\n\t\tsubsubdir2\n\t\t\tfile2.ext"
println(input)
val node = parse(input)
println(node)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment