`

计算出出现次数最多的字母和该字母出现的次数

阅读更多

方法一:

package testString;

import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.junit.Test;

public class MyTest
{
    /**
     * 给你一个字符串,包含了空格等标点符号,要你计算出出现次数最多的字母和该字母出现的次数。
     */
    @Test
    public void test()
    {
        String s = "123432341212,&asdaghjsa  1234352wko我第三方";
       
        Set<MyChar> set = new HashSet<MyChar>();
        for (int i = 0; i < s.length(); i++)
        {
            MyChar myChar = new MyChar(s.charAt(i), 1);
            boolean b = set.add(myChar);
            if (!b)
            {
                add(set, myChar);
            }
        }
        List<MyChar> list = new LinkedList<MyChar>();
        list.addAll(set);
        set = null;
       
        /** 取最大值 */
        MyChar big = Collections.max(list);
       
        System.out.println("出现次数最多的字母: " + big.getName() + " 该字母出现的次数" + big.getCount());
    }
   
    /** 当已经存在时,把数字加1 */
    public void add(Set<MyChar> set, MyChar myChar)
    {
        for (MyChar my : set)
        {
            if (my.equals(myChar))
            {
                my.setCount(my.getCount() + 1);
            }
            break;
        }
    }
   
    /** 实现相等的判断和可比较的判断 */
    public class MyChar implements Comparable<MyChar>
    {
        private Character name;
       
        private int count;
       
        public MyChar(Character name, int count)
        {
            super();
            this.name = name;
            this.count = count;
        }
       
        public Character getName()
        {
            return name;
        }
       
        public void setName(Character name)
        {
            this.name = name;
        }
       
        public int getCount()
        {
            return count;
        }
       
        public void setCount(int count)
        {
            this.count = count;
        }
       
        @Override
        public int compareTo(MyChar o)
        {
            return this.count == o.count ? 0 : this.count > o.count ? 1 : -1;
        }
       
        @Override
        public boolean equals(Object obj)
        {
            if (obj instanceof MyChar && this.name != null && this.name.equals(((MyChar)obj).name))
            {
                return true;
            }
            return false;
        }
       
        @Override
        public String toString()
        {
            // TODO Auto-generated method stub
            return "字母名字 : " + this.name + " 出现次数: " + this.count;
        }
       
        @Override
        public int hashCode()
        {
            // TODO Auto-generated method stub
            return name.hashCode();
        }
       
    }
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics