自己做的,有不足的地方,多多指教(比如时间复杂度,空间效率等方面)
1、二分查找,见之前的博客
2、给定一个字符串,得到这个字符串中首先出现两次的那个字符
这题不难,最简单的方法,就是把这些字符放到集合里面,如果出现2次了,就返回该字符
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String src = scanner.next();
HashMap<Character,Integer> items = new HashMap<Character,Integer>();
for(int i=0;i<src.length();i++){
if(!items.containsKey(src.charAt(i))){
items.put(src.charAt(i), 1);
}else{
System.out.println(src.charAt(i));
break;
}
}
}
3、尝试在以下文本中搜索并打印出包含单词"your"(不区分大小写)的句子,并按照出现次数从高到低排序
Make yourself at home
None of your business
I will be more careful
How about going to a move?
Your life is your own affair
思路:先统计每个字符串句子中包括“your”的个数,然后按个数排序
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String[] src = new String[1024];// 最多接收1024个句子
HashMap<String, Integer> items = new HashMap<String, Integer>();
int i = 0;
while (!(src[i++]=s.nextLine()).equals("EOF")) {
int count = countSubstr(src[i-1], "you", true);
items.put(src[i - 1], count);
}
// 对HashMap排序
ArrayList<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(
items.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1,
Map.Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
for (Entry<String, Integer> e : list) {
System.out.println(e.getKey() + "===>" + e.getValue());
}
}
/**
* 判断子字符串在原字串中出现的次数
*
* @param src
* @param sub
* @param isIgnore
* 是否忽略大小写 true是忽略
*/
private static int countSubstr(String src, String sub, boolean isIgnore) {
int count = 0, start = 0;
if (isIgnore) {
src = src.toLowerCase();
sub = sub.toLowerCase();
}
while ((start = src.indexOf(sub, start)) >= 0) {
start += sub.length();
count++;
}
return count;
}