[2019.12.30] learning algorithm records - Digital output appears three times

Algorithms - Digital output appears three times


Enter an integer string, for example: "1,2,2,2,3,4,4,4,6" select all integers appeared three times to form a new string output.
Example:
Input: "1,2,2,2,3,4,4,4,6"
Output: "24"

import java.util.HashMap;
import java.util.Map;


public class GetThree
{
    public int[] transfer(String list){
        String[] a = list.split(",");
        int size = a.length;
        int[] result = new int[size];
        for(int i = 0; i < a.length; i++){
            result[i] = Integer.parseInt( a[i] );
        }
        return result;
    }
    
    public String getResult(String orign){
        Map<Integer,Integer> map = new HashMap<Integer, Integer>();
        int[] orignList = transfer(orign);
        for(int i=0; i<orignList.length; i++){
            boolean containsKey = map.containsKey(orignList[i]);
            if(containsKey){   
             int value = map.get(orignList[i]) + 1;
             map.put(orignList[i], value);
            }
            else{
                map.put(orignList[i], 1);
            }            
        }
        String result = "";
        for(Integer key : map.keySet()){
            if(map.get(key) == 3){
                result += String.valueOf(key);
            }
        }
        return result;    
        }

    }

Notes
1. String and conversion between various formats:

  • Other types of transfer String:
String s = String.valueOf( value); // 其中 value 为任意一种数字类型。
  • String transfer other types:
String s = "169"; 

byte b = Byte.parseByte( s ); 

short t = Short.parseShort( s ); 

int i = Integer.parseInt( s ); 

long l = Long.parseLong( s ); 

Float f = Float.parseFloat( s ); 

Double d = Double.parseDouble( s );

2. JAVA split usage:
EG

String[] splitAddress=address.split(",");
System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);

If used as a separator, it must be written as follows, "." String.split("\\."), So as to properly separated, can not be used String.split(".");
"." Because, and "|" and "*", which are an escape character, have to add " \ ", and not a comma.

Basic Usage 3. JAVA Map of:
the Map key can be any type.
Reference Bowen 1
Reference Bowen 2
determines the Map contains a key need to containsKey () method in the map;
Analyzing the Map contains a value values need to use the map in containsValue () method of
Reference Bowen: Analyzing the Map whether to include a key is required to map the containsKey () method

references:

  1. Java String and conversion between various formats
Published 17 original articles · won praise 0 · Views 332

Guess you like

Origin blog.csdn.net/cletitia/article/details/103786044