//http://blog.csdn.net/myhaspl/
class ViewController: NSViewController {
private let trieroot:TrieNode = TrieNode (str: " ",nstate: NoteState.Root)
//http://blog.csdn.net/myhaspl/
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//http://blog.csdn.net/myhaspl/
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
//http://blog.csdn.net/myhaspl/
private func createTrieNode(current:TrieNode,mystr:String)->TrieNode
{
let mynode:TrieNode=TrieNode(str: mystr,nstate: NoteState.NoneTerminal)
current.link[mystr]=mynode
return mynode
}
//http://blog.csdn.net/myhaspl/
private func trieInput(current:TrieNode,str:String,isfind:Bool)->TrieNode?
{
if let nextstate=current.link[str]{
return nextstate
}
else if isfind{
return nil
}
else{
return createTrieNode(current,mystr:str)
}
}
private func readstr(word:String){
var currnode:TrieNode=trieroot
var inputstr:String=""
for mychar in word {
inputstr.append(mychar)
currnode = trieInput(currnode,str: inputstr,isfind: false)!
}
currnode.state=NoteState.Terminal
}
//http://blog.csdn.net/myhaspl/
private func findstr(word:String)->Bool{
var mynode:TrieNode=trieroot
var inputstr:String=""
for mychar in word {
inputstr.append(mychar)
if let nextnode = trieInput(mynode,str: inputstr,isfind: true)
{
mynode=nextnode
}
else{
return false
}
}
if mynode.state==NoteState.Terminal{
return true
}
else{
return false
}
}
//http://blog.csdn.net/myhaspl/
@IBOutlet weak var mywords: NSTextField!
@IBOutlet weak var inputtxt: NSTextField!
@IBAction func findword(sender: AnyObject) {
let findw:Bool=findstr(inputtxt.stringValue)
let messagebox:NSAlert=NSAlert()
if findw==true{
messagebox.messageText="找到"+inputtxt.stringValue
}
else{
messagebox.messageText="没找到"+inputtxt.stringValue
}
messagebox.alertStyle=NSAlertStyle.InformationalAlertStyle
messagebox.runModal()
}
@IBAction func createword(sender: AnyObject) {
readstr(inputtxt.stringValue)
mywords.stringValue+=inputtxt.stringValue
mywords.stringValue+=" "
}
}
原文:http://blog.csdn.net/myhaspl/article/details/50639954