TopCode_TCCC '01 Round 2_Level One_StringDup

熟悉一下数据结构

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

 

上面的题目可以扩展一下:

判断一个字符串在另一个字符串中出现的次数

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值