string permutation with upcase and lowcase

本文介绍了一种生成字符串所有可能的大小写排列的算法。通过递归方式,该算法能够针对输入的仅包含小写字母的字符串,列出所有可能的大写和小写组合。示例代码展示了如何使用递归函数实现这一功能。

Give a string, which only contains a-z. List all the permutation of upcase and lowcase. 
For example, str = "ab",  the output should be 
"ab", "aB", "Ab", "AB" 
for str = "abc", the output should be 
"abc", "abC", "aBc", "aBC", "Abc", "AbC", "ABc", "ABC" 

[解题思路]

本题与其他permutation题目区别在于结果中每位的字符都是固定的,仅仅是大小写的区别

因而不需要循环来遍历,使字符串的每一位可以遍历任意一个值

 

 1 public class Solution {
 2     public static void main(String[] args) {
 3         List<String> result = new ArrayList<String>();
 4         String tmp = "";
 5         permutation(tmp, 0, 4, result);
 6         System.out.println(result);
 7     }
 8     private static void permutation(String tmp, int depth, int len,
 9             List<String> result) {
10         if (depth == len) {
11             result.add(tmp);
12             return;
13         }
14 
15         tmp += (char) ('a' + depth);
16         permutation(tmp, depth + 1, len, result);
17         tmp = tmp.substring(0, tmp.length() - 1);
18 
19         tmp += (char) ('A' + depth);
20         permutation(tmp, depth + 1, len, result);
21         tmp = tmp.substring(0, tmp.length() - 1);
22 
23     }
24 }

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值