本帖最后由 Mr_Free 于 2013-7-28 01:09 编辑
按照你的思路,我帮你写了一个,主要是我发现你这样的话 s加到后面如果出现重复的字母,你会再做调用一边字母统计,再加一边重复字母,为了避免这样的问题,我把你要存放的字母放在一个HashSet里面。HashSet有元素不可重复的特性,我重写一下equals方法,比较s1里面的字母是否一样来去除重复。虽然可能这个方法不是很好,希望对你有帮助哈。- package cn.itcast.day3;
- import java.util.HashSet;
- import java.util.Iterator;
- public class newproblem1 {
- /*
- *取出一个字符串中字母出现的次数。如:"abcdekka27qoq" a(2)b(1)k(2)...
- */
-
- public static void main(String[] args) {
- count("abcdekka27qoq");
- }
- public static void count(String s1) {
- String ss = "";
-
- char[] arr = s1.toCharArray();
-
-
- HashSet<S1> hs1 = new HashSet<S1>();
- for (char c : arr) {
- if (Character.isLetter(c)){
- if(hs1.add(new S1(c,1))){
- int i = countTime(c, s1);
- Iterator<S1> it= hs1.iterator();
- S1 s=(S1)it.next();
-
- s.setI(i);
- ss = ss + c+"("+ i +")";
- }
- }
-
-
- }
- System.out.println(ss);
-
- }
-
- private static int countTime(char key, String s1) {
-
- char[] arr = s1.toCharArray();
- int times = 0;
- for (int i = 0; i < arr.length; i++ ) {
- if (arr[i]== key){
- times++;
- }
- }
- return times;
- }
-
- }
- class S1{
-
- private char c;
- private int i;
- S1(char c,int i){
- this.c=c;
- this.i=i;
- }
- public boolean equals(Object obj){
- S1 s2=(S1)obj;
- return this.c==s2.c;
- }
- public void setC(char c){
- this.c=c;
- }
- public void setI(int i){
- this.i=i;
- }
- public char getC(){
- return this.c;
- }
- public int getI(){
- return this.i;
- }
- public int hashCode(){
- return 60;
- }
- }
复制代码 |