Algorithm:
Approach1 : Start comparing characters from start and end of the string and continue until len(string)/2 .
Approach2: Start from front and back and compare the characters if not equal exit and return false else return true
Approach2: Start from front and back and compare the characters if not equal exit and return false else return true
Java Code:
public boolean isPalindrom(String str)
{
int length = str.length();
for(int i=0; i< length/2 ;i++)
{
if(str.charAt(i) != str.charAt(length - 1 - i))
{
System.out.println(str + " is not a palindrom." );
return false;
}
}
System.out.println(str + " is a palindrom." );
return true;
}
Example:
isPalindrom("abqba") ==> true
isPalindrom("abba") ==> true
isPalindrom("abstba") ==> false
isPalindrom("absa") ==> false
Ruby Code:
def palindrom(str)
start = 0
last = str.size - 1
array_str = str.chars
is_palindrom = true
while (start < last)
if array_str[start] != array_str[last]
is_palindrom = false
break
end
start+=1
last-=1
end
is_palindrom
end
p palindrom("radar")
p palindrom("r")
p palindrom("123456")
p palindrom("rr")
p palindrom("radbar")
p palindrom("1radar1")
No comments:
Post a Comment