0

我有一个用于查找两个单词是否为字谜的 SQL 代码。

DECLARE @str1 VARCHAR(100), @str2 VARCHAR(100)
SELECT @str1 = 'mmaa', @str2 = 'mama'

IF LEN(@str1) <> LEN(@str2)
  BEGIN
    SELECT 'NOT EQUAL'
  END 

ELSE
  BEGIN

    IF (SELECT COUNT(*) FROM

    (

    select  substring(@str1, number, 1) as data
        from    master..spt_values as m 
        where   m.type='p' and number <= len(@str1) AND number > 0

    UNION 

    select  substring(@str2, number, 1) as data
        from    master..spt_values as m 
        where   m.type='p' and number <= len(@str2) AND number > 0
        )
t)

= LEN(@str1)


    SELECT '1 anagram'
ELSE

SELECT '0 not anagram'
END

但是对于像 mmaa 和 mama 这样的词,这个程序返回的不是 anagram。但它们是字谜。我怎么解决这个问题?

4

2 回答 2

0

相当粗糙,但怎么样:

Declare @S1 varChar(100) = 'mmaa'
Declare @S2 varChar(100) = 'mama'

Declare @c char(1)
Declare @i tinyint
Declare @o1 varChar(100) = ''
Declare @o2 varChar(100) = ''
While DataLength(@s1) > 0 Begin
   Set @c = Left(@s1, 1)
   Set @s1 = Substring(@s1, 2, len(@s1))
   Set @i = 1

   While @i <= Len(@o1) And @c > substring(@o1, @i, 1) Set @i += 1
   Set @o1 = left(@o1, @i-1) + @c + substring(@o1, @i, len(@o1))
End
While DataLength(@s2) > 0 Begin
   Set @c = Left(@s2, 1)
   Set @s2 = Substring(@s2, 2, len(@s2))
   Set @i = 1

   While @i <= Len(@o2) And @c > substring(@o2, @i, 1) Set @i += 1
   Set @o2 = left(@o2, @i-1) + @c + substring(@o2, @i, len(@o2))
End
Select case When @o1 = @o2 Then 'Anagram' Else 'Not Anagram' End

或将排序封装到一个函数中,

    Create FUNCTION [dbo].[SortString](@s varChar(8000))
    RETURNS varChar(8000)
    As
    Begin
        Declare @c char(1)
        Declare @i int
        Declare @out varChar(8000) = left(@s, 1)
        While DataLength(@s) > 0 Begin
            Set @s = Substring(@s, 2, len(@s)-1)
            Set @c = Left(@s, 1)
            Set @i = 0
            While @i < Len(@out) And @c > substring(@out, @i+1, 1) Set @i += 1
            Set @out = case when @i < Len(@out) 
        then stuff(@out, @i+1, 0, @c)
        else  @out + @c end  
        End
        return  @out
    End
于 2013-01-14T03:54:49.053 回答
0

请尝试使用CHECKSUM_AGG

DECLARE @str1 VARCHAR(100), @str2 VARCHAR(100)
SELECT @str1 = 'mmaa', @str2 = 'mama'

IF LEN(@str1) <> LEN(@str2)
  BEGIN
    SELECT 'NOT EQUAL'
  END 
ELSE
  BEGIN
    IF(SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*))
        FROM   (select  substring(@str1, number, 1) as data
            from    master..spt_values as m 
            where   m.type='p' and number <= len(@str1) AND number > 0)T1)=
    (SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*))
        FROM   (select  substring(@str2, number, 1) as data
            from    master..spt_values as m 
            where   m.type='p' and number <= len(@str2) AND number > 0)T2)
        SELECT '1 anagram'
    ELSE
        SELECT '0 not anagram'
END
于 2013-01-14T05:18:41.303 回答