用Java设计一个程序,找到一个字符串中对称字符串的个数【面试题】

题目要求:

用Java设计一个程序,实现一个字符串的对称个数,如字符串"effeghg",有"ff","effe","ghg"这三个对称字符,所以返回3.

 

我实现的思路就是遍历这个字符串,

先选定头位置为第一个字符,然后从最后向前遍历这个字符串,

头尾两个字符相同,则取中间字符串,进行递归。

递归结束后得到结果,

继续将头向后推1位,然后再从字符串最后向前遍历,

如此循环,当尾等于头时,退出最外层循环,输出结果。

 

具体实现:

  1. /**
  2.  * @author bzwm
  3.  * 
  4.  */
  5. public class FindSymmetryStr {
  6.     /**
  7.      * 找出字符串中对称的子字符串的个数
  8.      * @param orgStr
  9.      * @return
  10.      */
  11.     public static int findSymmetryStr(String orgStr) {
  12.         //结果初始化
  13.         int count = 0;
  14.         //当输入字符串不为null且长度大于1时进行查找,否则直接返回0
  15.         if (orgStr != null && orgStr.length() > 1) {
  16.             //得到输入字符串的长度
  17.             int size = orgStr.length();
  18.             //字符串的头字符索引
  19.             int head;
  20.             //字符串从后向前遍历时的"尾"字符索引,即当前字符索引
  21.             int current;
  22.             //字符串的头字符
  23.             char hStr;
  24.             //字符串从后向前遍历时的"尾"字符
  25.             char cStr;
  26.             //从前开始遍历字符串
  27.             for (head = 0; head < size; head++) {
  28.                 //取得头字符
  29.                 hStr = orgStr.charAt(head);
  30.                 //指向输入字符串的最后
  31.                 current = size - 1;
  32.                 //当尾字符索引等于头字符索引时退出循环
  33.                 while (current > head) {
  34.                     //取得尾字符
  35.                     cStr = orgStr.charAt(current);
  36.                     //如果头尾字符相等,则继续判断
  37.                     if (hStr == cStr) {
  38.                         //取出头尾中间的子字符串,对其进行分析
  39.                         String newStr = orgStr.substring(head + 1, current);
  40.                         //如果此子字符串的长度大于1,则进行递归
  41.                         if (newStr.length() > 1)
  42.                             //递归得到此子字符串中对称的字符串个数
  43.                             count += findSymmetryStr(newStr);
  44.                         //如果此子字符串只有1个或0个字符,则表明原头尾字符和此单个字符组成对称字符串
  45.                         else
  46.                             count++;
  47.                         //将尾字符索引向前推1位
  48.                         current--;
  49.                     }
  50.                     //如果头尾字符不相等,则将尾字符索引向前推1位
  51.                     else {
  52.                         current--;
  53.                     }
  54.                 }
  55.             }
  56.         }
  57.         return count;
  58.     }
  59.     //测试程序
  60.     public static void main(String args[]) {
  61.         int count = findSymmetryStr("cddcbcbeffeghg");//
  62.         System.out.println("symmetry string count is : " + count);
  63.     }
  64. }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值