Skip to content

Commit 4e0d6f5

Browse files
committed
Added near palindrome
1 parent ce10ad5 commit 4e0d6f5

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.rampatra.strings;
2+
3+
/**
4+
* @author rampatra
5+
* @since 05/12/2018
6+
*/
7+
public class NearPalindrome {
8+
9+
/**
10+
* Checks if a string can be a palindrome by changing just one character in the string {@code str}.
11+
*
12+
* @param str the input string
13+
* @return {@code true} if it can be converted to a palindrome with one character change or else {@code false}
14+
*/
15+
private static boolean isStringPalindromeByChangingOneChar(String str) {
16+
int diffCount = 0;
17+
for (int i = 0, j = str.length() - 1; i < str.length() / 2; i++, j--) {
18+
if (str.charAt(i) != str.charAt(j)) {
19+
if (diffCount > 0) {
20+
return false;
21+
} else {
22+
diffCount++;
23+
}
24+
}
25+
}
26+
return true;
27+
}
28+
29+
public static void main(String[] args) {
30+
System.out.println(isStringPalindromeByChangingOneChar(""));
31+
System.out.println(isStringPalindromeByChangingOneChar("a"));
32+
System.out.println(isStringPalindromeByChangingOneChar("ab"));
33+
System.out.println(isStringPalindromeByChangingOneChar("aabbca"));
34+
System.out.println(isStringPalindromeByChangingOneChar("abccaa"));
35+
System.out.println(isStringPalindromeByChangingOneChar("abbcca"));
36+
}
37+
}

0 commit comments

Comments
 (0)