您的位置:首页 > 其它

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

2017-08-02 11:24 726 查看
import java.util.Scanner;

/**
* 在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置
*
* @author pomay
*
*/
public class NowCode_FirstOnly
{
public static int FirstOnly(String str)
{
int index = str.length();
int[] result = new int[256];
char[] c = str.toCharArray();
for (int i = 0; i < c.length; i++)
{
result[c[i]]++;
}

for (int i = 0; i < 256; i++)
{
if (result[i] == 1 && str.indexOf((char) i) < index)
{
index = str.indexOf((char) i);
}
}
if (index == str.length())
{
return -1;
} else
return index;
}

public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

while (sc.hasNext())
{
String str = sc.next();
System.out.println(FirstOnly(str));
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐