Huawei Online Programming Question Series-10-Character Count


Problem Description:

Problem Description

1. The question involves knowledge points.

  • Go to heavy, do not row.
  • HashSet

2. Solve it yourself.

  • Method 1, use the traditional method. Store the fetched characters into a new non-repeating array, and check the length of the new array.
package com.chaoxiong.niuke.huawei;

import java.util.Scanner;
/**
 * Create by tianchaoxiong on 18-4-9.
 */
public class HuaWei_10 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String key = scanner.nextLine();
            int result = getResult(key);
            System.out.println(result);
        }
    }

    private static int getResult(String key) {
        char []charArr = key.toCharArray();
        char []charArr2 = new char[charArr.length];
        int charArrIndex2 =0;
        for(char each :charArr){
            if(isStand(each,charArr2,charArrIndex2)){
                charArr2[charArrIndex2] = each;
                charArrIndex2 ++;
            }
        }
        return charArrIndex2;
    }

    private static boolean isStand(char key, char[] charArr2, int charArrIndex2) {
        // 1:ASCII在1到127
        if((int)key<0||(int)key>127){
            return false;
        }
        // 2:不重复
        for(int i=0;i<charArrIndex2;i++){
            if(key==charArr2[i]){
                return false;
            }
        }
        return true;
    }
}
  • Method two, use set to deduplicate, and then use set.length()the calculated length.
package com.chaoxiong.niuke.huawei;

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

/**
 * Create by tianchaoxiong on 18-4-9.
 */
public class HuaWei_10_2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String key = scanner.nextLine();
            System.out.println(getResult(key));
        }
    }

    private static int getResult(String key) {
        Set<Character> chars = new HashSet<Character>();
        for(char each :key.toCharArray()){
            chars.add(each);
        }
        return chars.size();

    }

}

3. Quality answers.

null

4. Summary of this question.

  • If there is a need for deduplication in the topic , the first thing that comes to mind is setthat if the deduplication also needs to be sorted , then TreeSetit is the most applicable, if only to deduplicate HashSet.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325967647&siteId=291194637