第一个只出现一次的字符

来源:互联网 发布:互联网大数据技术 编辑:程序博客网 时间:2024/06/08 14:13

在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置

思路:新建一个字符数组存储遍历到的字符位置,出现多次则忽略,
最后遍历数组,把出现一次字符的下边相比,返回最小的一个。

import java.util.*;public class Solution {    public int FirstNotRepeatingChar(String str) {        int[] charPosition = new int[52];//a-z : 0-25   A-Z : 26-51        for(int i = 0; i < charPosition.length ; i++)            charPosition[i] = -1;        for(int i = 0; i < str.length(); i++){            char ch = str.charAt(i);            int position = getPosition(ch);            if(charPosition[position] == -1){                charPosition[position] = i;            }else if(charPosition[position] >= 0){                charPosition[position] = -2;            }        }        int min = str.length();        for(int i = 0; i < charPosition.length ; i++){            if(charPosition[i] >= 0 && charPosition[i] < min){                min = charPosition[i];            }        }        if(min == str.length())            return -1;        return min;    }    public int getPosition(char ch){        if(ch >= 'a' && ch <= 'z')            return ch - 'a';        else if(ch >= 'A' && ch <= 'Z')            return 26 + ch - 'A';        return -1;    }}
原创粉丝点击