Home  >  Article  >  Java  >  Java implements finding the first character that appears only once

Java implements finding the first character that appears only once

王林
王林forward
2019-11-29 17:13:342831browse

Java implements finding the first character that appears only once

Question:

Find the first one that appears only once in a string (0<=string length<=10000, all composed of letters) character, and returns its position, if not, returns -1 (need to be case sensitive)

Related video tutorial recommendations:java online tutorial

Solution ideas:

The question requirement is very clear, which is to traverse the string and count the characters. After counting, just find the character with a count of 1. Obviously this requires the use of hashmap, the key is each character in the string, and the value is the number of times this character appears in the string.

The code is as follows:

import java.util.LinkedHashMap;
public class Solution {
    public int FirstNotRepeatingChar(String str) {
        int len = str.length();
        LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
        for (int i = 0; i < len; i++) {
            char c = str.charAt(i);
            Integer val = map.get(c);
            map.merge(c, 1, (oldValue, newValue) -> oldValue + newValue);
        }
        Character resultKey = null;
        for (Character c : map.keySet()){
            if (map.get(c) == 1){
                resultKey = c;
                break;
            }
        }
        for (int i = 0 ;i < len; i++){
            if (str.charAt(i) == resultKey){
                return i;
            }
        }        
       return -1;
    }
}

Recommended related articles and tutorials: javaQuick Start

The above is the detailed content of Java implements finding the first character that appears only once. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete