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

思路:利用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;
    }

}

 

上一篇:Shell字符串截取(非常详细)


下一篇:URL化