-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathNumberOfDistinctPalindromes.cs
More file actions
103 lines (90 loc) · 3.18 KB
/
Copy pathNumberOfDistinctPalindromes.cs
File metadata and controls
103 lines (90 loc) · 3.18 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NumberOfDistinctPalindromes
{
/********************************************
*
(January 28, 2016)
Problem statement:
Write a function to return count of total distinct palindrome substrings.
*
Come back to write down ideas:
1. First of all, do not count duplicate.
2. Brute force solution:
any substring of O(N^2) substrings to see if it is a palindrome;
Add the substring of palindrome to a hashset if it is not in the hashset.
And return the length of hashset
3. Use recursive solution - using subproblem to solve. Cannot filter out duplicate - not good
4. Better solution - use center point of string - 2n + 1, and then, go over each one, add all palindromes substring.
Requirement: write a C# code in 10 minutes for the solution, using brute force one.
*/
class Solution
{
static void Main(string[] args)
{
int count = numberOfDisinctPalindrome("aba"); // result is 3
int test2 = numberOfDisinctPalindrome("ababa"); // result is 5
}
public static int numberOfDisinctPalindrome(string s)
{
if (s == null || s.Length == 0)
return 0;
// store key - substring -
int len = s.Length;
HashSet<string> myset = new HashSet<string>();
for(int i=0;i<len;i++)
for (int j = i; j < len; j++)
{
string tmpS = s.Substring(i, j-i+1);
if(isPalindrome(tmpS))
{
if(!myset.Contains(tmpS))
myset.Add(tmpS);
}
}
return myset.Count;
}
/*
* Julia - make code short
*/
public static bool isPalindrome(string s)
{
if (s == null || s.Length == 0)
return true;
for (int i = 0; i < s.Length/2 ; i++)
{
if (s[i] != s[s.Length - 1 - i ])
return false;
}
return true;
}
/*
* Julia's comment:
* 1. count variable's scope is larger than necessary
* 2. for loop is not fully used.
*/
[Obsolete]
public static bool isPalindromeFirst(string s)
{
if (s == null || s.Length == 0)
return true;
int count = 0;
int len = s.Length;
for (; ; )
{
if (count <= len / 2)
{
if (s[count] == s[s.Length - count - 1]) // bug 01: not "s.Length - count", should be "s.Length - count", run-time error: out-of-range error - think about doing compile time checking to save time
count++;
else
return false;
}
else
return true;
}
}
}
}