File tree 1 file changed +37
-0
lines changed
src/main/java/com/rampatra/strings
1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments