forked from julycoding/The-Art-Of-Programming-By-July-2nd
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request julycoding#271 from WangTaoTheTonic/master
Add Java code for Chapter 1.5
- Loading branch information
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
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; | ||
} | ||
|
||
} |