Home > Java > Java Tutorial > body text

Java implements finding the first character that appears only once

王林
Release: 2019-11-29 17:13:34
forward
2735 people have browsed it

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 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;
    }
}
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!