算法题(常用字符串设计的算法)
一.字符串的处理
1、统计字符串中出现最多的字符
思路一 | 思路二 |
---|---|
双层循环,标记第一层字符在第二层循环中出现的次数(这个也是最先想到的) | 用Map集合,首先将字符串拆分为字符数组,然后转存到HashMap集合中,该集合的key为字符串中出现的字符,value对应该字符出现的次数。最后只需要在HashMap集合中找到Value值最大的key即可 |
思路一:解法
String a ="bancasddadadddeesf";
char res = a.charAt(0);
int max =0;
for (int i = 0; i < a.length(); i++) {
char c = a.charAt(i);
int count = 0;
for (int j = 0; j < a.length(); j++) {
if(c == a.charAt(j)){
count++;
}
}
if(max<count){
max = count;
res = c;
}
}
System.out.println(res+":出现的次数最多,共"+max+"次");
思路二:解法
String a ="bancasddadadddeesf";
char res = a.charAt(0);
int max =0;
Map<Character,Integer> hashmap = new HashMap<Character, Integer>();
for (int i = 0; i < a.length(); i++) {
char c =a.charAt(i);
Integer count = hashmap.get(c);
if (count == null) {
count = 1;
}else {
count++;
}
hashmap.put(c,count);
if(max<count){
max = count;
res = c;
}
}
System.out.println(res+":出现的次数最多,共"+max+"次");
2、找出字符串中第一次重复出现的字符
思路:遇到“重复”出现,我们就要联想到Set集合,因为Set集合是不允许重复的数据的
String a ="abccba";
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < a.length(); i++) {
if(!set.add(a.charAt(i))){
System.out.println(a.charAt(i));
break;
}
}
3、在字符串中找出第一个只出现一次的字符
思路:Map统计每个字符出现的次数,然后遍历从前往后数组,第一次出现次数为一的就是本题的答案
String a ="abcfgcba";
Map<Character,Integer> hashmap = new HashMap<Character, Integer>();
for (int i = 0; i < a.length(); i++) {
char c = a.charAt(i);
Integer count = hashmap.get(c);
if(count==null){
count = 1;
}else{
count++;
}
hashmap.put(c,count);
}
for (int i = 0; i < a.length(); i++) {
Integer count = hashmap.get(a.charAt(i));
if(count == 1){
System.out.println(a.charAt(i));
break;
}
}
4、统计手机号中各个数字的个数,按照升序输出(注意-这里的升序是号码大小不是次数)
思路1:这要说统计元素个数,我们就可以用Map集合 。
String a ="13115682864";
Map<Character,Integer> hashmap = new HashMap<Character, Integer>();
for (int i = 0; i < a.length(); i++) {
char c = a.charAt(i);
Integer count = hashmap.get(c);
if(count==null){
count = 1;
}else{
count++;
}
hashmap.put(c,count);
}
Set<Character> set = hashmap.keySet();
Object[] objects = set.toArray();
Arrays.sort(objects);
for (Object ww:objects
) {
System.out.print(ww);
}
思路二:我们可以用桶排序的思想去解决问题,因为我们带排的元素可以看做为数组的下标
String a ="13115682864";
int[] array = new int[10];
for (int i = 0; i < a.length(); i++) {
char c = a.charAt(i);
array[c-'0']++;
}
for (int i = 0; i < array.length; i++) {
if(array[i]==0)
continue;
System.out.println(i+"出现了"+array[i]+"次");
}
二、设计字符串反转的算法
1、输入一个字符串串,反转字符串中的每个字符顺序,同时保留单词和空格的初始位置
例如:输入 Let’s take Leetcode,输出 s’teL ekat edocteed
String a ="Let's take Leetcode";
String[] s = a.split(" ");
StringBuilder stringBuilder = new StringBuilder();
for (String aa:s) {
for (int i = aa.length()-1; i >=0; i--) {
stringBuilder.append(aa.charAt(i));
}
stringBuilder.append(" ");
}
stringBuilder.substring(0,stringBuilder.length()-1);
String result = stringBuilder.toString();
System.out.println(result);