File tree Expand file tree Collapse file tree 2 files changed +63
-0
lines changed
problems/dynamic_programming
tests/dynamic_programming Expand file tree Collapse file tree 2 files changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ package dynamic_programming
2
+
3
+ func PalindromicSubstrings (s string ) int {
4
+ // Special case
5
+ if len (s ) == 0 {
6
+ return 0
7
+ }
8
+ // Count to store total number of palindromic substrings
9
+ count := 0
10
+ // Process each string by keeping each index as middle and
11
+ // expand both sides from it
12
+ for i := 0 ; i < len (s ); i ++ {
13
+ // Odd length
14
+ count += expandFromCenterForPalindromicSubstrings (s , i , i )
15
+ // Even length
16
+ count += expandFromCenterForPalindromicSubstrings (s , i , i + 1 )
17
+ }
18
+ return count
19
+ }
20
+
21
+ func expandFromCenterForPalindromicSubstrings (s string , left int , right int ) int {
22
+ count := 0
23
+ for left >= 0 && right < len (s ) && s [left ] == s [right ] {
24
+ left --
25
+ right ++
26
+ count ++
27
+ }
28
+ return count
29
+ }
Original file line number Diff line number Diff line change
1
+ package dynamic_programming_test
2
+
3
+ import (
4
+ "testing"
5
+
6
+ "github.com/anirudhology/leetcode-go/problems/dynamic_programming"
7
+ )
8
+
9
+ func TestPalindromicSubstrings (t * testing.T ) {
10
+ // Test case for null string
11
+ if result := dynamic_programming .PalindromicSubstrings ("" ); result != 0 {
12
+ t .Errorf ("Expected 0, got %d" , result )
13
+ }
14
+
15
+ // Test case for single character string
16
+ if result := dynamic_programming .PalindromicSubstrings ("a" ); result != 1 {
17
+ t .Errorf ("Expected 1, got %d" , result )
18
+ }
19
+
20
+ // Test case for string with all same characters
21
+ if result := dynamic_programming .PalindromicSubstrings ("aaaa" ); result != 10 {
22
+ t .Errorf ("Expected 10, got %d" , result )
23
+ }
24
+
25
+ // Test case for string with mixed characters
26
+ if result := dynamic_programming .PalindromicSubstrings ("abc" ); result != 3 {
27
+ t .Errorf ("Expected 3, got %d" , result )
28
+ }
29
+
30
+ // Test case for string with palindromic substrings
31
+ if result := dynamic_programming .PalindromicSubstrings ("aaa" ); result != 6 {
32
+ t .Errorf ("Expected 6, got %d" , result )
33
+ }
34
+ }
You can’t perform that action at this time.
0 commit comments