C# || Palindromic Substrings – How To Find The Number Of Palindromic Substrings Using C#
The following is a module with functions which demonstrates how to find the number of palindromic substrings using C#.
1. Count Substrings – Problem Statement
Given a string s, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
Example 1:
Input: s = "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: s = "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
2. Count Substrings – Solution
The following is a solution which demonstrates how to find the number of palindromic substrings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// ============================================================================ // Author: Kenneth Perkins // Date: Jun 2, 2022 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to find palindromic substrings // ============================================================================ public class Solution { public int CountSubstrings(string s) { var count = 0; for (var index = 0; index < s.Length; ++index) { count += CountPalindrome(s, index, index); // Count even sized count += CountPalindrome(s, index, index + 1); // Count odd sized } return count; } private int CountPalindrome(string s, int start, int end) { var count = 0; while (start >= 0 && end < s.Length && s[start--] == s[end++]) { ++count; } return count; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output for the example cases:
3
6
Leave a Reply