Skip to content

Commit 4fb4b37

Browse files
committed
#680: Valid Palindrome II; solution & tests
1 parent 9ffa86e commit 4fb4b37

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/**
2+
* 680
3+
* Valid Palindrome II
4+
**
5+
* Given a string s,
6+
* return true if the s can be palindrome
7+
* after deleting at most one character from it.
8+
*
9+
* Example 1:
10+
* Input: s = "aba"
11+
* Output: true
12+
*
13+
* Example 2:
14+
* Input: s = "abca"
15+
* Output: true
16+
* Explanation: You could delete the character 'c'.
17+
*
18+
* Example 3:
19+
* Input: s = "abc"
20+
* Output: false
21+
*
22+
* Constraints:
23+
* • 1 <= s.length <= 10^5
24+
* • s consists of lowercase English letters.
25+
**
26+
* https://leetcode.com/problems/valid-palindrome-ii/
27+
***/
28+
29+
using System;
30+
31+
namespace Problems;
32+
33+
public class ValidPalindromeII
34+
{
35+
public bool ValidPalindrome( ReadOnlySpan<char> s )
36+
{
37+
int left = 0;
38+
int right = s.Length - 1;
39+
40+
while ( left < right )
41+
{
42+
if ( s[left] != s[right] )
43+
{
44+
return IsPalindrome( s, left + 1, right ) || IsPalindrome( s, left, right - 1 );
45+
}
46+
else
47+
{
48+
left++;
49+
right--;
50+
}
51+
}
52+
53+
return true;
54+
}
55+
56+
private static bool IsPalindrome( ReadOnlySpan<char> s, int left, int right )
57+
{
58+
while ( left < right )
59+
{
60+
if ( s[left] != s[right] )
61+
{
62+
return false;
63+
}
64+
65+
left++;
66+
right--;
67+
}
68+
69+
return true;
70+
}
71+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
using NUnit.Framework;
2+
3+
using Problems;
4+
5+
public class ValidPalindromeIITests
6+
{
7+
[TestCase( "aba", ExpectedResult = true )]
8+
[TestCase( "abca", ExpectedResult = true )]
9+
[TestCase( "abc", ExpectedResult = false )]
10+
[TestCase( "lcupuupucul", ExpectedResult = true )]
11+
[TestCase( "adffdslcupuupuculsdffda", ExpectedResult = true )]
12+
[TestCase( "deddde", ExpectedResult = true )]
13+
public bool ValidPalindromeTest( string s ) =>
14+
new ValidPalindromeII().ValidPalindrome( s );
15+
}

0 commit comments

Comments
 (0)