将字符串排列为大写和小写
我有一个字符串“abc”。排列字符串的程序(如果可能的话,在 Java 中)会是什么样子?
例如:
abc
ABC
Abc
aBc
abC
ABc
abC
AbC
I have a string, "abc". How would a program look like (if possible, in Java) who permute the String?
For example:
abc
ABC
Abc
aBc
abC
ABc
abC
AbC
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
像这样的事情应该可以解决问题:
Something like this should do the trick:
您可能已经知道,可能的不同组合的数量为 2^n,其中 n 等于输入字符串的长度。
由于 n 理论上可能相当大,因此 2^n 有可能超出基本类型(例如 int)的容量。 (用户可能需要等待几年才能完成所有组合的打印,但这是他们的事。)
相反,让我们使用位向量来保存所有可能的组合。我们将位数设置为 n 并将其全部初始化为 1。例如,如果输入字符串为“abcdefghij”,则初始位向量值为 {1111111111}。
对于每种组合,我们只需循环遍历输入字符串中的所有字符,如果对应位为 1,则将每个字符设置为大写,否则将其设置为小写。然后我们递减位向量并重复。
例如,对于输入“abc”,该过程如下所示:
位: 对应的组合:
111 ABC
110 ABc
101 AbC
100 ABC
011 aBC
010 aBc
001 abC
000 abc
通过使用循环而不是递归函数调用,我们还避免了在大输入字符串上发生堆栈溢出异常的可能性。
下面是实际的实现:
As you probably already know, the number of possible different combinations is 2^n, where n equals the length of the input string.
Since n could theoretically be fairly large, there's a chance that 2^n will exceed the capacity of a primitive type such as an int. (The user may have to wait a few years for all of the combinations to finish printing, but that's their business.)
Instead, let's use a bit vector to hold all of the possible combinations. We'll set the number of bits equal to n and initialize them all to 1. For example, if the input string is "abcdefghij", the initial bit vector values will be {1111111111}.
For every combination, we simply have to loop through all of the characters in the input string and set each one to uppercase if its corresponding bit is a 1, else set it to lowercase. We then decrement the bit vector and repeat.
For example, the process would look like this for an input of "abc":
Bits: Corresponding Combo:
111 ABC
110 ABc
101 AbC
100 Abc
011 aBC
010 aBc
001 abC
000 abc
By using a loop rather than a recursive function call, we also avoid the possibility of a stack overflow exception occurring on large input strings.
Here is the actual implementation:
也可以使用回溯来解决这个问题:
You can also use backtracking to solve this problem:
请在此处找到上述代码片段:
}
Please find here the code snippet for the above :
}
你可以做类似
```
```的事情
You can do something like
```
```