数据库环境:SQL SERVER 2005
如题,求字符串“abcbklmnodfghijkmer”中最大的递增子序列。这个字符串有点特别,
只由26个小写字母a-z组成。
大概思路如下:
1.将字符串转到一列存储,并生成行号
2.设置一个递增计数器列,默认为1,比较上下行的字符,如果在字典中的顺序是递增,
则计数器加1,否则,计数器置1
3.找出计数器最大的数及对应的行号,根据这2个数截取字符串
思路有了,下面直接贴代码
DECLARE @vtext VARCHAR(255)SET @vtext = 'abcbklmnodfghijkmer'/*讲字符串转成一列存储,并生成行号*/WITH x0 AS ( SELECT number AS id , SUBSTRING(@vtext, number, 1) AS letter FROM master.dbo.spt_values WHERE type = 'P' AND number <= LEN(@vtext) AND number >= 1 ),/*实现计数器*/ x1 ( id, letter, clen ) AS ( SELECT id , letter , 1 AS clen FROM x0 WHERE id = 1 UNION ALL SELECT x0.id , x0.letter , CASE WHEN x1.letter <= x0.letter THEN x1.clen + 1 ELSE 1 END AS clen FROM x0 , x1 WHERE x0.id = x1.id + 1 ) /*截取字符串*/ SELECT SUBSTRING(@vtext, start, sublen) AS 最大子序列 FROM ( SELECT id , clen , MAX(clen) OVER ( ) AS maxclen , id - MAX(clen) OVER ( ) + 1 AS start , MAX(clen) OVER ( ) AS sublen FROM x1 ) t WHERE clen = maxclen
求出的最大子序列是
(本文完)
新闻热点
疑难解答