題目要求:
用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);
- }
- }