Given a string, find the most characters and times in this string _ algorithm

Source: Internet
Author: User

1. "Given a string, find the most characters and times in this string",

public class Findchar {public

static void main (string args[]) {
	string str= Sgssssssssssjkoouyfdcjkkjhgdedryunnbbvffdssghhhj ";
	Find (str);
}
   public static void Find (String s) {
    Character findchar= null;
		int len=s.length ();
		int cout=0;
		Hashmap<character,integer> hp=new  hashmap<character,integer> ();
		for (int i=0;i<len;i++) {
			char ch=s.charat (i);
			if (!hp.containskey (CH))
				hp.put (CH, 1);
			
			else
				{int index=hp.get (ch) +1;
		 Hp.put (ch, index);
		 if (index>cout) {
				cout=index;
				Findchar=ch
			
		}
		}} System.out.println (cout);
		System.out.println (Findchar);
		
	}
The problems encountered:

1. Non-static methods cannot be invoked in a static method.

The memory allocation time of static method differs from instance method
when the program starts running, the static method is already allocated space in memory with the entry address, so it can be called directly by the class name. Method name
and the instance method allocates memory
only after the object of the class is created That is, the static method already has the entry address after the program starts running, and the instance method may not be allocated memory, so the instance method cannot be invoked through the static method
. Invoking instance methods in the same way as "class name. Method Name"
Therefore, the find (String s) method must be accompanied by a static identifier.

2.
Character findchar= null; this notation is possible, but when I write char findchar=null, a null pointer exception occurs because the Charater exists as an object, and char is just the original data type, and, in addition, HashMap can only be stored in reference types, cannot save basic types. The default value for an object reference instance variable is NULL, whereas the default value of the original type instance variable is related to their type.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.