String Permutation

Problem

感觉和上面的题又有点像, 给一个string, 里面不能有数字。 然后所有的大写字母和非字母符号不能动, 其他的小写字母可以随意动。 输出所有的可能。
e.g. input Oh my-god!
   output Om hd-goy! Oy hm-dog! 等等。。

 

Solution

 1 public static List<String> permutate(String str) {
 2     List<String> res = new ArrayList<String>();
 3     if(str == null || str.length() == 0) return res;
 4     
 5     StringBuffer sb = new StringBuffer(str);
 6     int[] idx = new int[str.length()];
 7     
 8     int low = 'a', high = 'z';
 9     int start = 0;
10     for(int i=0; i<str.length(); i++) {
11         if(str.charAt(i) <= high && str.charAt(i) >= low) {
12             idx[start] = i;
13             start++;
14         }
15     }
16     
17     System.out.println(start);
18 
19     boolean[] visited = new boolean[start];
20     helper(str, res, sb, idx, visited, 0, start);
21     return res;
22 }
23 
24 public static void helper(String str, List<String> res, StringBuffer sb, int[] idx, boolean[] visited, int pos, int end) {
25     if(pos == end) {
26         res.add(new StringBuffer(sb).toString());
27         return;
28     }
29             
30     for(int i=0; i<end; i++) {
31         if(visited[i] == false) {
32             visited[i] = true;
33             sb.setCharAt(idx[pos], str.charAt(idx[i]));
34             helper(str, res, sb, idx, visited, pos+1, end);
35             visited[i] = false;
36         }
37     }
38 }

 

转载于:https://www.cnblogs.com/superbo/p/4112093.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值