Created
August 21, 2016 03:32
-
-
Save soeirosantos/06597c5048e3029840c3e01815811b0c to your computer and use it in GitHub Desktop.
check palindromes with some tolerance indicated by totalCharsToCheck
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.com.soeirosantos; | |
import java.util.LinkedList; | |
import java.util.Queue; | |
import java.util.Stack; | |
public class Main { | |
public static void main(String[] args) { | |
System.out.println(isAlmostPalindrome("abcddcba", 0)); | |
System.out.println(!isAlmostPalindrome("abcddcbx", 0)); | |
System.out.println(isAlmostPalindrome("abcddcbx", 1)); | |
System.out.println(!isAlmostPalindrome("abcdycbx", 1)); | |
System.out.println(isAlmostPalindrome("abcdycbx", 2)); | |
System.out.println(!isAlmostPalindrome("abcdydbx", 2)); | |
} | |
public static boolean isAlmostPalindrome(String word, int totalCharsToCheck) { | |
char[] chars = word.toCharArray(); | |
Queue<Character> queue = new LinkedList<>(); | |
Stack<Character> stack = new Stack<>(); | |
for(char c : chars) { | |
stack.push(c); | |
queue.offer(c); | |
} | |
boolean isPalindrome = true; | |
int totalDiff = 0; | |
for (int i = 0; i < chars.length/2; i++) { | |
char c1 = stack.pop(); | |
char c2 = queue.poll(); | |
if (c1 != c2) { | |
totalDiff++; | |
if (totalDiff > totalCharsToCheck) { | |
isPalindrome = false; | |
break; | |
} | |
} | |
} | |
return isPalindrome; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment