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

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

public class FindSymmetryStr
{

/** *//**
* 找出字符串中對稱的子字符串的個數
* @param orgStr
* @return
*/

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

//當輸入字符串不為null且長度大于1時進行查找,否則直接返回0

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

//從前開始遍歷字符串

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

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

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

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

else
{
current--;
}
}
}
}

return count;
}

//測試程序

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