黑马程序员技术交流社区

标题: 这样一道题,不知道有没有简便方法 [打印本页]

作者: qmlovewhr    时间: 2014-9-28 23:08
标题: 这样一道题,不知道有没有简便方法
  改题是:求一个字符串的所有子串,例如:字符串“abc"   ,输出为 'a' 'b' 'c' 'ab' 'ac' 'bc' 'abc' 'acb' bca' bac'  'cab'  'cba'
  不知有没有可扩展的方法?

作者: 姠佐メ亾佑つ    时间: 2014-9-29 02:10
直接递归就可以了哈!
  1. package com.itheima.bbs;


  2. public class StringTest {   
  3.        
  4.     public static String str = "abc";
  5.    
  6.     public static void main(String[] args) {
  7.                                   
  8.         show(0, new String());
  9.             
  10.     }
  11.    
  12.         // 递归
  13.    
  14.     public static void show(int current_recur, String temp) {
  15.            
  16.         if (current_recur < str.length()) {
  17.                
  18.             for (int i = 0; i < str.length(); i++) {
  19.                    
  20.                 if (!(temp.contains(str.substring(i, i + 1)))) {
  21.                        
  22.                     System.out.print("'"+temp + str.substring(i, i + 1)+"'" + " ");
  23.                     
  24.                     show(current_recur + 1,
  25.                             new String(temp + str.substring(i, i + 1)));
  26.                 }
  27.             }
  28.         }
  29.     }
  30.    
  31.    
  32. }
复制代码

作者: 家进    时间: 2014-9-29 09:30
'acb' bca' bac'  'cab'  'cba'不是它字串呀,
作者: qmlovewhr    时间: 2014-9-29 11:49
听老师说这道题没几人能做出来哈,看来黑马的基础入学题质量是越来越高呀




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2