现在的位置: 首页 > 综合 > 正文

找出字符串中重复最多的字母

2013年10月31日 ⁄ 综合 ⁄ 共 1069字 ⁄ 字号 评论关闭

已知一个字符串s=“iuoifdjfjehafp”,其中有重复字母。请找出其中重复次数最多的那个字母。

这里用到了Compareable接口,非常方便。

对于array,fruits实现该接口后,使用下句即可排序:

Arrays.sort(fruits);

对于实现了collection接口的集合类,比如ArrayList,fruits实现该接口后,使用下句排序:

Collections.sort(fruits);

下面是完整的源码。

import java.util.ArrayList;
import java.util.Collections;

public class Testing {

	public static void main(String[] args) {
		char[] c = { 'd', 'r', 'd', 'a', 'f', 'a', 'f', 'f', 's', 's' };
		ArrayList<CN> al = new ArrayList<CN>();
		for (int i = 0; i < c.length; i++) {

			if (al.size() == 0 || search(al, c[i]) == 0) {
				CN cn = new CN(c[i], 1);
				al.add(cn);
			} else if (search(al, c[i]) != 0) {
				al.get(search(al, c[i])).increaseCount();
			}
		}
		
		Collections.sort(al);
		
		for (CN x : al) {
			System.out.println(x.c + "," + Integer.toString(x.i));
		}
		
		System.out.println(al.get(al.size()-1).c);
	}

	public static int search(ArrayList<CN> al, char c) {
		if (al.size() == 0) {
			return 0;
		} else {
			for (int i = 0; i < al.size(); i++) {
				if (al.get(i).c == c) {
					return i;
				}
			}

			return 0;
		}
	}
}

class CN implements Comparable<CN> {
	public char c;
	public int i;

	public CN(char c, int i) {
		this.c = c;
		this.i = i;
	}

	public int compareTo(CN cn) {
		if (this.i < cn.i) {
			return -1;
		}else if(this.i == cn.i){
			return 0;
		}else{
			return 1;
		}		
	}

	public void increaseCount() {
		this.i++;
	}
}

抱歉!评论已关闭.