`

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

 
阅读更多

题目要求:

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

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

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

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

递归结束后得到结果,

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

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

具体实现:

  1. /**
  2. *@authorbzwm
  3. *
  4. */
  5. publicclassFindSymmetryStr{
  6. /**
  7. *找出字符串中对称的子字符串的个数
  8. *@paramorgStr
  9. *@return
  10. */
  11. publicstaticintfindSymmetryStr(StringorgStr){
  12. //结果初始化
  13. intcount=0;
  14. //当输入字符串不为null且长度大于1时进行查找,否则直接返回0
  15. if(orgStr!=null&&orgStr.length()>1){
  16. //得到输入字符串的长度
  17. intsize=orgStr.length();
  18. //字符串的头字符索引
  19. inthead;
  20. //字符串从后向前遍历时的"尾"字符索引,即当前字符索引
  21. intcurrent;
  22. //字符串的头字符
  23. charhStr;
  24. //字符串从后向前遍历时的"尾"字符
  25. charcStr;
  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. StringnewStr=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. returncount;
  58. }
  59. //测试程序
  60. publicstaticvoidmain(Stringargs[]){
  61. intcount=findSymmetryStr("cddcbcbeffeghg");//
  62. System.out.println("symmetrystringcountis:"+count);
  63. }
  64. }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics