Skip to content

Instantly share code, notes, and snippets.

@mckelvin
Created November 22, 2012 13:03
Show Gist options
  • Save mckelvin/4131080 to your computer and use it in GitHub Desktop.
Save mckelvin/4131080 to your computer and use it in GitHub Desktop.
DBJ 仁
/**
* @class CheckerBoard
*
* the result is expected to be:
* # # # #
* # # #
* # # # #
* # # #
* # # # #
* # # #
* # # # #
*/
import java.util.*;
public class CheckerBoard{
public static void main(String args[]){
int i,j;
char c;
for(i=1;i<=7;i++){
for(j=1;j<=7;j++){
if ((i + j) % 2 ==0){
c = '#';
}else{
c = ' ';
}
System.out.print(c);
}
System.out.println();
}
}
}
import java.util.Scanner;
/**
* @class TestPalindromicPhrase
*
*/
class TestPalindromicPhrase{
public static void main (String [] args)
{
//while get one input:
String inputString="B man, a plan, a canal - Pana!ma!";
if isPalindromicPhrase(inputString}{
System.out.println("XXXXX is XXX");
} else {
System.out.println("XXXXX is not XXX");
}
}
/**
* 这个函数用来判断字符x是不是一个标点
*/
static boolean isPunctuation(char x){
return !((x >= 'a' && x <='z') || (x >= 'A' && x <='Z'));
}
static boolean isPalindromicPhrase(String x){
// 先把所有的大写字母全部转成小写
x = x.toLowerCase();
int low_index = 0,//这是一个index,表示初始化时最左边的字母的位置
high_index = x.length() - 1;//同样的,表示初始化时最右边的字母的位置
//在下面的迭代中,迭代的区间始终控制在[low_index, high_index] ,这是一个闭区间
while (low_index < high_index){
/**
* 比如某一次迭代时,是这么个情况 "!!!A###A AA!!??",
* 按照题意肯定要先无视掉最左边的所有非字母字符,
*/
while(isPunctuation(x.charAt(low_index))){
low_index++;
}
/**
* 调整左区间后,现在是"A###A AA!!??"
*/
/**
* 同样也要调整右区间
*/
while(isPunctuation(x.charAt(high_index))){
high_index--;
}
/**
* 现在:"A###A AA"
* 到这里 这个区间的最左边肯定是一个字母,最右边也肯定是一个字母
* 判断下最左和最右是不是不同,如果不同就直接返回false,表示这不是一个回文句
*/
if (x.charAt(low_index)!=x.charAt(high_index)){
return false;
}
/**
* 最左和最右对比完了,左右区间都要逼近
*/
low_index++;
high_index--;
/**
* 现在变成了这样,进入下一次迭代"###A A"
*/
}
/**
* 当这个区间里只有一个或者零个元素的时候,即(low_index < high_index)不成立的时候,循环退出
* 能走到这一步,前面的false肯定没发生过,这就是个回文句了。
*/
return true;
}
}
/**
* @class TestPalindromicWord
*
*/
class TestPalindromicWord{
public static void main (String [] args)
{
System.out.println(isPalindromicWord(""));
System.out.println(isPalindromicWord("aA"));
System.out.println(isPalindromicWord("aZA"));
System.out.println(isPalindromicWord("Radar"));
System.out.println(isPalindromicWord("Xadar"));
}
static boolean isPalindromicWord(String x){
x = x.toLowerCase();
//if x.length() == 3, just need once(3/2 == 1) iter
for (int i=0; i< x.length()/2 ;i++ ){
if (x.charAt(i) != x.charAt(x.length()-i-1)){
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment