码迷,mamicode.com
首页 > 其他好文 > 详细

微软笔试题,luckstring

时间:2016-09-21 21:22:12      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

技术分享

解析:这题主要在于字典排序和重复判断,其实只要使用TreeSet这个能排序的SET集合类就可以轻松解决了

 1 import java.util.Scanner;
 2 import java.util.TreeSet;
 3 import java.util.ArrayList;
 4  
 5 public class Main{
 6      
 7     public static void main(String[] args){
 8         //扫描获取字符串
 9         Scanner s = new Scanner(System.in);
10          
11         String line = s.nextLine();
12          
13         s.close();
14         //用来生成指定长度的斐波那契数组,
15         //因为一个字符串中不同的字符最多有26个,所以设置长度为26
16         ArrayList<Integer> al = initArr(26);
17         //用来存放子字符串,用SET可以防止重复,TreeSet可以自动按字典顺序排序 
18         TreeSet<String> ts = new TreeSet<String>();
19         //i和j表示子字符串在原字串中的起止位置(包括i,不包括j),循环遍历所有子串 
20         for(int i = 0;i < line.length() - 1;i++)
21             for(int j = i + 1;j <= line.length();j++){
22                 String subStr = line.substring(i, j);
23                 //判断字串中不同字符的个数是否是斐波那契数
24                 if(al.contains(getDifNum(subStr)))
25                     //加进SET
26                     ts.add(subStr);
27             }
28         //循环打印 
29         for(String str : ts){
30             System.out.println(str);
31         }
32     }
33     //获得子字串中不同字符个数 
34     public static int getDifNum(String subStr){
35         TreeSet<Character> tmps = new TreeSet<Character>();
36          
37         char[] carr = subStr.toCharArray();
38         //将所有字符加入SET,因为SET不会重复,所以最后的SET大小就是不同字符的个数 
39         for(Character a : carr){
40             tmps.add(a);
41         }
42         return tmps.size();
43     }
44     //运用迭代进行斐波那契数组的生成 
45     public static ArrayList<Integer> initArr(int n){
46         ArrayList<Integer> al = new ArrayList<Integer>(n);
47          
48         al.add(1);
49         al.add(1);
50          
51         int p = 0;
52         int q = 1;
53          
54         while(true){
55             al.add(al.get(p) + al.get(q));
56             p = q;
57             q = al.size() - 1;
58             if(al.size() == n)
59                 break;
60         }
61          
62         return al;
63          
64     }
65 }

 

微软笔试题,luckstring

标签:

原文地址:http://www.cnblogs.com/njupt-Qsimple/p/5893972.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!