免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 4760 | 回复: 13
打印 上一主题 下一主题

打印出字符串hello的所有子串 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-09-07 17:08 |只看该作者 |倒序浏览
RT

游客,如果您要查看本帖隐藏内容请回复


[ 本帖最后由 teebye 于 2009-9-7 17:12 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2009-09-07 17:28 |只看该作者
看到你的代码了,不过这个是python?怎么看着很别扭?

[ 本帖最后由 9命怪猫 于 2009-9-7 17:34 编辑 ]

论坛徽章:
0
3 [报告]
发表于 2009-09-08 01:38 |只看该作者
原帖由 teebye 于 2009-9-7 17:08 发表
RT

**** 本内容被作者隐藏 *****

def all_sub_string( l ):
    if( len( l ) == 1 ):
        return [l]
    else:
        r = []
        for x in range( 1, len( l ) + 1 ):
            r.append( [ l[0] ] + l[ 1:x ] )
        a = all_sub_string( l[1:] )
        return  r + a


>>> all_sub_string(list('hello'));
[['h'], ['h', 'e'], ['h', 'e', 'l'], ['h', 'e', 'l', 'l'], ['h', 'e', 'l', 'l', 'o'], ['e'], ['e', 'l'], ['e', 'l', 'l'], ['e', 'l', 'l', 'o'], ['l'], ['l', 'l'], ['l', 'l', 'o'], ['l'], ['l', 'o'], ['o']]

[ 本帖最后由 orangetouch 于 2009-9-8 01:39 编辑 ]

论坛徽章:
0
4 [报告]
发表于 2009-09-08 09:20 |只看该作者
非递归的,ruby的写法

| def print_sub_string(str)
      (0..str.size-1).each do|i|
       j = str.size-i
       until(j==0)
         puts str[i,j]
         j -=1
       end
     end
   end
  print_sub_string("hello")

论坛徽章:
0
5 [报告]
发表于 2009-09-08 09:21 |只看该作者
结果

hello
hell
hel
he
h
ello
ell
el
e
llo
ll
l
lo
l
o

论坛徽章:
0
6 [报告]
发表于 2009-09-08 10:24 |只看该作者

回复 #1 teebye 的帖子

def sub(s):
    l = len(s)
    for i in range(0,l+1):
        for j in range(0,l+1):
            if i < j:
                print s[i:j]
sub("hello")

论坛徽章:
0
7 [报告]
发表于 2009-09-09 14:29 |只看该作者
本帖最后由 starfuck 于 2019-11-26 23:47 编辑












论坛徽章:
0
8 [报告]
发表于 2009-09-09 22:31 |只看该作者
Except LZ's code ( so far I don't see it ), all the python code above have issue(s).
testing your function with this short string ('abc') shows all -- missing some sub-string.

论坛徽章:
0
9 [报告]
发表于 2009-09-09 23:15 |只看该作者
LZ's code is soooooo ugly ! is it python code ?

check your result with the following
ello
hllo
helo
hell
elo
ell
hlo
hll
llo
hel
heo
el
eo
lo
ll
ho
hl
he
h
e
l
o

[ 本帖最后由 mjus 于 2009-9-9 23:19 编辑 ]

论坛徽章:
0
10 [报告]
发表于 2009-09-09 23:26 |只看该作者
以我多年的看帖经验。。lz一般贴的是RUBY。。。。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP