熟悉一下数据结构
Problem Statement
Create a class called StringDup. Given a string made up of ONLY letters and
digits, determine which character is repeated the most in the string ('A' is
different than 'a'). If there is a tie, the character which appears first in
the string (from left to right) should be returned.
Examples :
aaiicccnn = c
aabbccdd = a
ab2sbf2dj2skl = 2
Here is the method signature :
public char getMax(String input);
We will check to make sure that the input contains only letters and digits (no
punctuation marks or spaces).
Definition
Class:StringDup
Method:getMax
Parameters:String
Returns:char
Method signature:char getMax(String param0)
(be sure your method is public)
大致翻译一下:
创建一个类名字叫StringDup。给定一个仅由字母和数字组成的字符串,判定那个字符被重复的次数最多(大小写不同)。如果
有这样的关系:这个字符第一次出现在字符串中需要返回
测试数据:
aabbccdd = a
ab2sbf2dj2skl = 2
自己写的:
/**
* 时间复杂度为O(n2)
* */
public char getMax(String input) {
// 转化为数组
char[] charArr = input.toCharArray();
// 前面循环最大的次数
int temp = 0;
// 出现最多的字符
char tempChar = ' ';
for (int i = 0; i < charArr.length; i++) {
// 默认出现0次。
int count = 0;
for (int j = i; j < charArr.length; j++) {
// 如果后面有和当前字符相等的字符,则出现的次数加1
if (charArr[j] == charArr[i]) {
count++;
}
// 如果本轮循环的次数大于前面字符出现的次数,则本次为出现最多的次数。且该字符为charArr[i]
if (count > temp) {
temp = count;
tempChar = charArr[i];
}
}
}
return tempChar;
}
不过时间复杂度为O(n2)。
后来看到网上有另外一种写法,时间复杂度稍低O(n):
/**
* 时间复杂度为O(n)
* */
public char getMax(String input) {
// 将包含的字符放入哈希表,字符作为key,出现次数作为value
char[] alph = input.toCharArray();
Map<Character, Integer> aa = new HashMap<Character, Integer>();
for (Character c : alph) {
if (Character.isWhitespace(c))
continue;
if (aa.containsKey(c) == false) {
aa.put(c, 1);
} else {
aa.put(c, aa.get(c) + 1);
}
}
// 比较获取出现最多次数的字符
Set<Character> set = aa.keySet();
Iterator iter = set.iterator();
Integer count = 0;
Character key = new Character(' ');
while (iter.hasNext()) {
Character ccc = (Character) iter.next();
if (aa.get(ccc) > count) {
count = aa.get(ccc);
key = ccc;
}
}
return key;
}
不过没有解决掉aabbccdd的情况。用第二个方法。返回的是dd而不是aa
上面的题目可以扩展一下:
判断一个字符串在另一个字符串中出现的次数