活跃农民
- 积分
- 514
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-8-15
- 最后登录
- 1970-1-1
|
写了一个,不过写的时候没有看到下面说反过来不需要,所以求了全排列,先得到数字字符,然后获取全部的排列组合,对每个排列组合获取其中的单数组合
- class tt {
- public Set<Integer> getAllOddsFromString(String string) {
- Set<Integer> res = new HashSet<>();
- if (string == null || string.length() == 0) {
- return res;
- }
- StringBuilder strb = new StringBuilder();
- for (char ch : string.toCharArray()) {
- if (ch >= '0' && ch <= '9') {
- strb.append(ch);
- }
- }
- List<String> allpermutes = new ArrayList<>();
- getAllPermutations(allpermutes, strb, 0);
- for (String str : allpermutes) {
- int tmp = Integer.parseInt(str);
- while (tmp > 0) {
- if (tmp % 2 == 1) {
- res.add(tmp);
- }
- tmp /= 10;
- }
- }
- return res;
- }
- private void getAllPermutations(List<String> allpermutes, StringBuilder strb, int pos){
- List<String> res = new ArrayList<>();
- if (strb == null || strb.length() == 0) {
- return ;
- }
- if (pos == strb.length()) {
- allpermutes.add(strb.toString());
- }
- for (int i=pos; i<strb.length(); i++) {
- swap(strb, pos, i);
- getAllPermutations(allpermutes, strb, i + 1);
- swap(strb, pos, i);
- }
- }
- private void swap(StringBuilder strb, int i, int j){
- char ch = strb.charAt(i);
- strb.setCharAt(i, strb.charAt(j));
- strb.setCharAt(j, ch);
- }
-
- public static void main(String[] args) {
- tt test = new tt();
- Set<Integer> res = test.getAllOddsFromString("1a2bc3");
- System.out.println(res);
- }
- }
复制代码
Output : [1, 321, 3, 213, 21, 123, 13] |
|