数据结构:单链表结构字符串(python版)
- #!/urs/bin/env python
- # -*- coding:utf-8 -*-
- #异常类
- class stringTypeError(TypeError):
- pass
- #节点类
- class Node(object):
- def __init__(self, elem, next_ = None):
- self.elem = elem
- self.next = next_
- #单链表类
- class single_list(object):
- def __init__(self):
- self._head = None
- self._num = 0
- def __len__(self):
- return self._num
- def prepend(self,elem):
- self._head = Node(elem, self._head)
- self._num += 1
- def append(self,elem):
- if self._head is None:
- self._head = Node(elem)
- self._num += 1
- return
- p = self._head
- while p.next:
- p = p.next
- p.next = Node(elem)
- self._num += 1
- def pop_last(self):
- if self._head is None:
- raise ValueError("in pop_last")
- p = self._head
- if p.next is None:
- e = p.elem
- self._head = None
- self._num -= 1
- return e
- while p.next.next:
- p = p.next
- e = p.next.elem
- p.next = None
- self._num -= 1
- return e
- def delitem(self, key):
- if key == len(self)-1:
- self.pop_last()
- elif 0<= key < len(self) - 1:
- p = self._head
- pre = None
- num = -1
- while p is not None:
- num += 1
- if key==num:
- if not pre:
- self._head = p.next
- self._num -= 1
- else:
- pre.next = p.next
- self._num -= 1
- break
- else:
- pre = p
- p = p.next
- else:
- raise IndexError
- def insert(self, key, elem):
- if key>=len(self)-1:
- self.append(elem)
- elif 0<=key<len(self)-1:
- p = self._head
- pre = None
- num = -1
- while p:
- num += 1
- if num==key:
- if not pre:
- self._head = Node(elem, self._head)
- self._num += 1
- else:
- pre.next = Node(elem, pre.next)
- self._num += 1
- break
- else:
- pre = p
- p = p.next
- else:
- raise IndexError
- # 打印显示
- def printall(self):
- p = self._head
- while p:
- print(p.elem, end="")
- if p.next:
- print(", ", end="")
- p = p.next
- print("")
- #单链表字符串类
- class string(single_list):
- def __init__(self, value):
- self.value = str(value)
- single_list.__init__(self)
- for i in range(len(self.value)-1,-1,-1):
- self.prepend(self.value[i])
- def length(self):
- return self._num
- def printall(self):
- p = self._head
- print("字符串结构:",end="")
- while p:
- print(p.elem, end="")
- if p.next:
- print("-->", end="")
- p = p.next
- print("")
- #朴素的串匹配算法,返回匹配的起始位置
- def naive_matching(self, p): #self为目标字符串,t为要查找的字符串
- if not isinstance(self, string) and not isinstance(p, string):
- raise stringTypeError
- m, n = p.length(), self.length()
- i, j = 0, 0
- while i < m and j < n:
- if p.value[i] == self.value[j]:#字符相同,考虑下一对字符
- i, j = i+1, j+1
- else: #字符不同,考虑t中下一个位置
- i, j = 0, j-i+1
- if i == m: #i==m说明找到匹配,返回其下标
- return j-i
- return -1
- #kmp匹配算法,返回匹配的起始位置
- def matching_KMP(self, p):
- j, i = 0, 0
- n, m = self.length(), p.length()
- while j < n and i < m:
- if i == -1 or self.value[j] == p.value[i]:
- j, i = j + 1, i + 1
- else:
- i = string.gen_next(p)[i]
- if i == m:
- return j - i
- return -1
- # 生成pnext表
- @staticmethod
- def gen_next(p):
- i, k, m = 0, -1, p.length()
- pnext = [-1] * m
- while i < m - 1:
- if k == -1 or p.value[i] == p.value[k]:
- i, k = i + 1, k + 1
- pnext[i] = k
- else:
- k = pnext[k]
- return pnext
- #把old字符串出现的位置换成new字符串
- def replace(self, old, new):
- if not isinstance(self, string) and not isinstance(old, string) \
- and not isinstance(new, string):
- raise stringTypeError
- #删除匹配的旧字符串
- start = self.matching_KMP(old)
- for i in range(old.length()):
- self.delitem(start)
- #末尾情况下时append追加的,顺序为正;而前面的地方插入为前插;所以要分情况
- if start<self.length():
- for i in range(new.length()-1, -1, -1):
- self.insert(start,new.value[i])
- else:
- for i in range(new.length()):
- self.insert(start,new.value[i])
- if __name__=="__main__":
- a = string("abcda")
- print("字符串长度:",a.length())
- a.printall()
- b = string("abcabaabcdabdabcda")
- print("字符串长度:", b.length())
- b.printall()
- print("朴素算法_匹配的起始位置:",b.naive_matching(a),end=" ")
- print("KMP算法_匹配的起始位置:",b.matching_KMP(a))
- c = string("xu")
- print("==")
- b.replace(a,c)
- print("替换后的字符串是:")
- b.printall()
今天早上在继续实现replace时,发现一个严重的问题。在我初始化字符串string对象时,使用了self.value = str(value),而我在后面使用匹配算法时,无论是朴素匹配还是KMP匹配
都使用的对象的value值作为比较。所以对象实现replace方法后的start =b.mathcing_KMP(a)后依旧不变,会一直为6.原因在于我使用的是self.value在进行匹配。所以replace后的
链表字符串里的值并没有被利用到,从而发生严重的错误。
改进篇见下一篇博客
数据结构:单链表结构字符串(python版)的更多相关文章
- 数据结构:单链表结构字符串(python版)改进
此篇文章的replace实现了字符串类的多次匹配,但依然有些不足. 因为python字符串对象为不变对象,所以replace方法并不修改原先的字符串,而是返回修改后的字符串. 而此字符串对象时用单链表 ...
- 数据结构:单链表结构字符串(python版)添加了三个新功能
#!/urs/bin/env python # -*- coding:utf-8 -*- #异常类 class stringTypeError(TypeError): pass #节点类 class ...
- 数据结构:栈 顺序表方法和单链表方法(python版)
#!/usr/bin/env python # -*- coding:utf-8 -*- class StackUnderflow(ValueError): pass #链表节点 class Node ...
- python算法与数据结构-单链表(38)
一.链表 链表是一种物理存储单元上非连续.非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的.链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成.每个结点包括 ...
- python实现数据结构单链表
#python实现数据结构单链表 # -*- coding: utf-8 -*- class Node(object): """节点""" ...
- 数据结构之线性表(python版)
数据结构之线性表(python版) 单链表 1.1 定义表节点 # 定义表节点 class LNode(): def __init__(self,elem,next = None): self.el ...
- C语言数据结构-单链表的实现-初始化、销毁、长度、查找、前驱、后继、插入、删除、显示操作
1.数据结构-单链表的实现-C语言 typedef struct LNode { int data; struct LNode* next; } LNode,*LinkList; //这两者等价.Li ...
- 数据结构——单链表java简易实现
巩固数据结构 单链表java实现 单链表除了表尾 每个几点都有一个后继 结点有数据和后继指针组成 通过构建表头和表尾(尾部追加需要)两个特殊几点 实现单链表的一些操作,代码如下 package co ...
- C# 数据结构--单链表
什么是单链表 这两天看到很多有关单链表的面试题,对单链表都不知道是啥的我.经过学习和整理来分享一下啥是单链表和单链表的一些基本使用方法.最后看些网上有关单链表的面试题代码实例. 啥是单链表? 单链表是 ...
随机推荐
- 利用Hexo搭建个人博客-博客初始化篇
上一篇博文 <利用Hexo搭建个人博客-环境搭建篇> 中,我们讲解了利用Hexo搭建个人博客应该要配置哪些环境.相信大家已经迫不及待的想要知道接下来应该要怎么把自己的博客搭起来了,下面,让 ...
- 七天学会ASP.NET MVC (六)——线程问题、异常处理、自定义URL
本节又带了一些常用的,却很难理解的问题,本节从文件上传功能的实现引出了线程使用,介绍了线程饥饿的解决方法,异常处理方法,了解RouteTable自定义路径 . 系列文章 七天学会ASP.NET MVC ...
- TODO:小程序的春天你想做什么
TODO:小程序的春天你想做什么 微信小程序是一种全新的连接用户与服务的方式,它可以在微信内被便捷地获取和传播,同时具有出色的使用体验. 初步了解小程序的特点 导航明确,来去自如 统一稳定, 视觉规范 ...
- edit
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- iOS-网络基础
概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博.微信等,这些应用本身可能采用iOS开发,但是所有的数据支撑都是基于后台网络服务器的.如今,网络编程越来越普遍,孤立的应用通常是没有生命力 ...
- Nginx与Apache比较
Nginx特点:高性能epoll 异步非阻塞多个连接(万级别)可以对应一个进程 支持反向代理支持7层负载均衡静态文件.反向代理.前端缓存等处理方便支持高并发连接,每秒最多的并发连接请求理论可以达到 5 ...
- Vue脚手架工具vue-cli和调试组件vue-devtools
https://github.com/vuejs/vue-cli npm install vue-cli -g vue init webpack my-project cd my-project // ...
- Sublime 快捷键
语法快捷键: 后代:> 缩写:nav>ul>li <nav> <ul> <li></li> </ul> </nav& ...
- WPF 后台读取样式文件
ResourceDictionary dic = new ResourceDictionary { Source = new Uri("Styles.xaml",UriKind.R ...
- Minor【 PHP框架】6.代理
框架Github地址:github.com/Orlion/Minor (如果觉得还不错给个star哦(^-^)V) 框架作者: Orlion 知乎:https://www.zhihu.com/peop ...