简体   繁体   English

一种用于回文测试的递归算法

[英]A recursive algorithm for palindrome testing

This is a normal method for palindrome testing that I made but I need a recursive function that checks if a number is palindrome.这是我进行的回文测试的常规方法,但我需要一个递归函数来检查数字是否为回文。

int number, firstnumber, lastnumber, secondnumber, fourthnumber;

readingnumber:

Console.Write("Please enter your palindrome number(5 digits) :" );
//reading the integer number entered
number = Int32.Parse(Console.ReadLine());
//making condition if the number is less than 5 digits
if (number / 100000 != 0)
    goto readingnumber;
else
{
    //we are taking each element alone 
    firstnumber = number / 10000;
    lastnumber = number % 10;
    fourthnumber = (number % 100) / 10;
    secondnumber = (number % 10000) / 1000;

    //making if condition to verify if the number is palindrom or not
    if (firstnumber == lastnumber && secondnumber == fourthnumber)
        Console.WriteLine("\n\nthe number you've enter is palindrom");
    else
        Console.WriteLine("\n\nthe number you've enter is not palindrom");

    //end of program
    Console.WriteLine("\n\n\n\t\tPlease enter any key to exit ...");
}

Console.ReadLine();

String palindrom is if either字符串回文是如果

  • it contains less than 1 character它包含少于 1 个字符
  • Char at[0] == Char at [Length - 1] and inner string [1..Length - 2] is palindrom Char at[0] == Char at [Length - 1] 和内部字符串 [1..Length - 2] 是回文

So所以

public static Boolean IsPalindrom(String value) {
  if (null == value)
    return true; //TODO: or false or throw exception

  if (value.Length <= 1)
    return true;
  else  
    return (value[0] == value[value.Length - 1]) && 
           (IsPalindrom(value.Substring(1, value.Length - 2)));
}

If you want to test a number (eg 12321 ) for being palindrom, just convert it to string :如果您想测试一个数字(例如12321 )是否为回文,只需将其转换为string

  int value = 12321;
  Boolean result = IsPalindrom(value.ToString(CultureInfo.InvariantCulture));

In general, it's good practice to NOT use Substring recursively as you end up creating LOTS of strings (in fact, here the memory usage for all the strings increases quadratically with the length of the string).一般来说,最好不要递归地使用Substring ,因为您最终会创建很多字符串(事实上,这里所有字符串的内存使用量都随着字符串的长度呈二次方增加)。

The MSDN reference for String.Intern says:String.Intern的 MSDN 参考说:

The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program.公共语言运行时通过维护一个称为实习池的表来保存字符串存储,该表包含对程序中以编程方式声明或创建的每个唯一文字字符串的单个引用。 Consequently, an instance of a literal string with a particular value only exists once in the system.因此,具有特定值的文字字符串的实例在系统中只存在一次。

For any given string, say, "abcdedcba" , if recursively using Substring , you'll end up putting "bcdedcb" , "cdedc" , "ded" , and "e" into the intern pool needlessly.对于任何给定的字符串,比如"abcdedcba" ,如果递归地使用Substring ,您最终会不必要地将"bcdedcb""cdedc""ded""e"放入实习生池中。


Instead, it's better to pass the same string in to the recursive method, and vary two indices which determine which characters are being compared.相反,最好将相同的字符串传递给递归方法,并改变两个确定要比较哪些字符的索引。 String functions are slow, but integers are value types and can be created and thrown away with gay abandon.字符串函数很慢,但整数是值类型,可以随意创建和丢弃。


Implementation执行

/// <summary>
/// Returns true if the string is a palindrome (an empty string is a palindrome).
/// Returns false if the string is null or not a palindrome.
/// </summary>
public static bool IsPalindrome(string value)
{
    if ( value == null )
        return false;

    if ( value.Length == 0 )
        return true;

    return isPalindrome(value, 0, value.Length - 1);
}

private static bool isPalindrome(string value, int startChar, int endChar)
{
    if ( value[startChar] != value[endChar] )
        return false;

    if ( startChar >= endChar )
        return true;

    return isPalindrome(value, startChar + 1, endChar - 1);
}

Usage用法

public static void Main()
{
    var a = IsPalindrome(""); // true
    var b = IsPalindrome("1"); // true
    var c = IsPalindrome("11"); // true
    var d = IsPalindrome("121"); // true
    var e = IsPalindrome("123"); // false
}

Run it here on ideone.com .在 ideone.com 上运行它

A trifle more contemporary way is the following method which make use of the array range feature.一种更现代的方法是以下利用数组范围功能的方法。

// soner
static bool IsPalindrome(string s) => s.Length <= 1 || (s[0] == s[^1] && IsPalindrome(s[1..^1])); 

Run Here在这里运行

    class Program
        {
            public static void Main()
            {
                var x = 545;
                var y = 548785445;
                Console.WriteLine(IsPalindrome(x.ToString()));
                Console.WriteLine(IsPalindrome(y.ToString()));
            }

            public static bool IsPalindrome(string text)
            {
                if (text.Length <= 1)
                    return true;
                else
                {
                    if (text[0] != text[text.Length - 1])
                        return false;
                    else
                        return IsPalindrome(text.Substring(1, text.Length - 2));
                }
            }


        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM