How to find longest palindrome substring in C#

1 Answer

0 votes
using System;

public class Program
{
	private static int longestPalindromeSubstring(string str) {
		int len = str.Length;
		int longestLength = 1, start = 0;

		for (int i = 0; i < len; i++) {
			for (int j = i; j < len; j++) {
				int palindrome = 1;

				for (int k = 0; k < (j - i + 1) / 2; k++) {
					if (str[i + k] != str[j - k]) {
						palindrome = 0;
					}
				}

				if (palindrome != 0 && (j - i + 1) > longestLength)	{
					start = i;
					longestLength = j - i + 1;
				}
			}
		}

		Console.Write("Longest palindrome substring = ");
		for (int i = start; i <= start + longestLength - 1; i++) {
			Console.Write(str[i]);
		}
		Console.Write("\n");

		return longestLength;
	}
	public static void Main(string[] args)
	{
		string str = "qabcbaproggorpxyyxzv";

		int result = longestPalindromeSubstring(str);

		Console.Write("Length palindrome substring length = " + result);
	}
}





/*
run:
  
Longest palindrome substring = proggorp
Length palindrome substring length = 8
  
*/

 



answered Jun 3, 2023 by avibootz

Related questions

1 answer 129 views
1 answer 131 views
2 answers 173 views
1 answer 117 views
2 answers 149 views
...