Text  |   7 September 11 | 7 notes
So long Pal!
One of the most discussed examples in Computer Science classes is the palindrome. Wikipedia defines palindrome as a word, phrase, number, or other sequence of units that can be read the same way in either direction, with general allowances for adjustments to punctuation and word dividers.
According to one article, palindromes were discovered as early as the 79AD where the latin phrase “Sator Arepo Tenet Opera Rotas” was found as a graffito at Herculaneum. However, it was found out that palindromes of considerable complexity were explored in the ancient Sanskrit poetry.
Palindromes are usually discussed in computer science classes because it poses a rather easy problem for students to tinker with. The most common example of a problem involving palindromes is checking whether a given string is a palindrome or not. Here are 3 different ways to check if a string is a palindrome(NOTE: The methods posted assumes that the string be a one-word string and does not include punctuation and word dividers.)
Code #1
public boolean isPalindrome(String word){
boolean isPal = true;
for(int i=0; i<Math.floor(word.length()/2); i++){
if(word.charAt(i) != word.charAt(word.length()-1-i)){
isPal = false;
break;
}
}
return isPal;
}
Explanation:
The method loops until the middle of the string and compares the character found at the value of i and compares it to the character with the same index if the string is reversed. If all characters are equal, then the string is said to be a palindrome
Code #2
public boolean isPalindrome(String word){
boolean isPal = true;
String rev = “”;
for(int i=0; i<word.length(); i++){
rev = word.charAt(word.length()-1-i) + “”;
}
if(!word.equals(rev))
isPal = false;
return isPal;
}
Explanation:
The method reverses the string and stores it in another variable. The method then compare the original string and the reversed string. If the two string are equal, then the string is said to be a palindrome.
Code #3
public boolean isPalindrome(String word){ boolean isPal = true; Stack<Character> stack = new Stack<Character>(); for(int i=0; i<Math.floor(word.length()/2); i++) stack.push(word.charAt(i)); for(int i=Math.ceiling(word.length()/2); i<word.length(); i++){ if(word.charAt(i) stack.pop()){ isPal = false; break; } } return isPal; } Explanation: The method uses a stack, a Last In First Out data structure, and stores all the characters until the middle of the string. The method then pop each character from the stack and compare it to the character corresponding to it on the 2nd half of the string. DISCLAIMER: I didn’t test if the Java codes are working. It may cause some syntax errors but the algorithm will definitely work.
-
theboredmilklovescoffee likes this
-
ivogeorgiev likes this
-
rencaffeinated likes this
-
programmingmeetsmath posted this
Likes
RSS
Archive
Random
The Social Networks