Skip to content

Commit

Permalink
Merge pull request julycoding#271 from WangTaoTheTonic/master
Browse files Browse the repository at this point in the history
Add Java code for Chapter 1.5
  • Loading branch information
julycoding committed Apr 25, 2014
2 parents 9799f67 + 535e239 commit 757b604
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions ebook/code/java/chapter1/Palindrome.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* Check weather a string is a palindrome
* @author WangTaoTheTonic
*/
public class Palindrome
{
// Solution 1, from sides to middle
public static boolean isPalindromeV1(String str)
{
if(null == str || 0 == str.length())
{
return false;
}

int length = str.length();
if(1 == length)
{
return true;
}

for(int leftFlag = 0, rightFlag = length - 1 ; leftFlag < rightFlag; leftFlag ++, rightFlag --)
{
if(str.charAt(leftFlag) != str.charAt(rightFlag))
return false;
}

return true;
}

// Solution 2, from middle to sides
public static boolean isPalindromeV2(String str)
{
if(null == str || 0 == str.length())
{
return false;
}

int length = str.length();
if(1 == length)
{
return true;
}

int leftFlag = 0;
int rightFlag = length;
leftFlag = length / 2 - 1;
if(0 == length % 2)
{
rightFlag = leftFlag + 1;
}
else
{
rightFlag = leftFlag + 2;
}

for( ; leftFlag >= 0; leftFlag --, rightFlag ++)
{
if(str.charAt(leftFlag) != str.charAt(rightFlag))
return false;
}

return true;
}

}

0 comments on commit 757b604

Please sign in to comment.