題目要求:
用Java設(shè)計(jì)一個(gè)程序,實(shí)現(xiàn)一個(gè)字符串的對(duì)稱個(gè)數(shù),如字符串"effeghg",有"ff","effe","ghg"這三個(gè)對(duì)稱字符,所以返回3.
我實(shí)現(xiàn)的思路就是遍歷這個(gè)字符串,
先選定頭位置為第一個(gè)字符,然后從最后向前遍歷這個(gè)字符串,
頭尾兩個(gè)字符相同,則取中間字符串,進(jìn)行遞歸。
遞歸結(jié)束后得到結(jié)果,
繼續(xù)將頭向后推1位,然后再從字符串最后向前遍歷,
如此循環(huán),當(dāng)尾等于頭時(shí),退出最外層循環(huán),輸出結(jié)果。
具體實(shí)現(xiàn):

/** *//**
* @author bzwm
*
*/

public class FindSymmetryStr
{

/** *//**
* 找出字符串中對(duì)稱的子字符串的個(gè)數(shù)
* @param orgStr
* @return
*/

public static int findSymmetryStr(String orgStr)
{
//結(jié)果初始化
int count = 0;

//當(dāng)輸入字符串不為null且長度大于1時(shí)進(jìn)行查找,否則直接返回0

if (orgStr != null && orgStr.length() > 1)
{
//得到輸入字符串的長度
int size = orgStr.length();
//字符串的頭字符索引
int head;
//字符串從后向前遍歷時(shí)的"尾"字符索引,即當(dāng)前字符索引
int current;
//字符串的頭字符
char hStr;
//字符串從后向前遍歷時(shí)的"尾"字符
char cStr;

//從前開始遍歷字符串

for (head = 0; head < size; head++)
{
//取得頭字符
hStr = orgStr.charAt(head);
//指向輸入字符串的最后
current = size - 1;
//當(dāng)尾字符索引等于頭字符索引時(shí)退出循環(huán)

while (current > head)
{
//取得尾字符
cStr = orgStr.charAt(current);
//如果頭尾字符相等,則繼續(xù)判斷

if (hStr == cStr)
{
//取出頭尾中間的子字符串,對(duì)其進(jìn)行分析
String newStr = orgStr.substring(head + 1, current);
//如果此子字符串的長度大于1,則進(jìn)行遞歸
if (newStr.length() > 1)
//遞歸得到此子字符串中對(duì)稱的字符串個(gè)數(shù)
count += findSymmetryStr(newStr);
//如果此子字符串只有1個(gè)或0個(gè)字符,則表明原頭尾字符和此單個(gè)字符組成對(duì)稱字符串
else
count++;
//將尾字符索引向前推1位
current--;

}
//如果頭尾字符不相等,則將尾字符索引向前推1位

else
{
current--;
}
}
}
}

return count;
}

//測(cè)試程序

public static void main(String args[])
{
int count = findSymmetryStr("cddcbcbeffeghg");//
System.out.println("symmetry string count is : " + count);
}
}
----2008年12月22日