1

我有以下代码来生成字符串的所有可能子字符串:

import java.util.*;
public class PlayString
{
    public static void main(String[] args)
    {
        String st = "ABC";
        char[] arr = new char[st.length()];
        for (int x = 0; x < st.length(); x++)
        {
            arr[x] = st.charAt(x);
        }
        StringBuffer sb = new StringBuffer();
        combination(arr, 0, st.length() - 1, sb);
    }

    public static void combination(char[] arr, int index, int b, StringBuffer sb)
    {
        for (int i = index; i <= b; i++)
        {
            sb.append(arr[i]);
            System.out.println(sb);
            combination(arr, i + 1, b, sb);
            sb.setLength(sb.length() - 1);
        }
    }
}

我的问题是:在最后一行当 sb.setLength(sb.length()-1) 到底发生了什么?例如,如果字符串输入是“abc”,那么输出将像 a , ab , abc ,那么当设置长度时会发生什么?然后设置后,有什么东西被截断了吗?当我们尝试在此之后附加一个元素时会发生什么?

我的意思是如果输入字符串是“abc”,那么在字符串缓冲区中有“abc”并且它的长度现在是 3 之后,那么我们执行 sb.setLength(sb.length() - 1 ) 所以现在长度应该是 now ,那么究竟哪个元素被截断了?当我们稍后追加时会发生什么?

4

1 回答 1

1

如果我们替换函数combination()如下

public static void combination(char[] arr, int index, int b, StringBuffer sb)
    {
        for (int i = index; i <= b; i++)
        {
            System.out.println("i :" + i);
            sb.append(arr[i]);
            System.out.println(sb);
            combination(arr, i + 1, b, sb);
            System.out.println("setting length:" + (sb.length() -1) + ": index :" + index);
            sb.setLength(sb.length() - 1);
        }
    }

You will see the following output >

i :0
A
i :1
AB
i :2
ABC
setting length:2: index :2
setting length:1: index :1
i :2
AC
setting length:1: index :1
setting length:0: index :0
i :1
B
i :2
BC
setting length:1: index :2
setting length:0: index :0
i :2
C
setting length:0: index :0

Hope it explains the reason.

于 2012-09-18T18:19:53.777 回答