其他分享
首页 > 其他分享> > 找出字符串中第一个只出现一次的字符

找出字符串中第一个只出现一次的字符

作者:互联网

思路:利用ASCII 的编码,

1,一次遍历得到所有字符的下标对应出现的次数

2,遍历结果,找出第一次只出现一次的字符

3,此算法的时间复杂度为O(n)

import java.util.Scanner;

public class Main {


    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            char asdfasdfo = firstChar(scanner.next());
            char c = (char) -1;
            if (asdfasdfo == c) {
                System.out.println("-1");
            } else {
                System.out.println(asdfasdfo);

            }
        }

    }


    private static char firstChar(String str) {
        int[] chars = new int[58];
        char[] charArray = str.toCharArray();
        for (char c : charArray) {
            chars[c - 65] += 1;
        }
        for (int i = 0; i < charArray.length; i++) {
            if (chars[charArray[i] - 65] == 1) {
                return charArray[i];
            }
        }

        return (char) -1;
    }

}

 

标签:字符,找出,scanner,int,chars,System,char,charArray,字符串
来源: https://www.cnblogs.com/dongma/p/13233777.html