/****************************************************************************************
*题目:第一个只出现一次的字符
* 在字符串中找出第一个只出现一次的字符。如输入“abaccdeff”,则输出’b’。
*时间:2015年10月3日08:58:57
*文件:FirstNotRepeatingChar.java
*作者:cutter_point
****************************************************************************************/
package bishi.Offer50.y2015.m10.d03;
import org.junit.Test;
public class FirstNotRepeatingChar
{
public char firstNotRepeat(String pString)
{
if(pString == null)
return '\0';
final int tableSize = 256; //用ascii码来存放所有的字符
int hashTable[] = new int[tableSize];
for(int i = 0; i < tableSize; ++i)
{
//初始化数组
hashTable[i] = 0;
}//for
int index = 0;
while(index != pString.length())
{
//把对应的字符转化为ascii然后对应的下标数字++
hashTable[pString.charAt(index++)]++;
}//while
//遍历hash表,返回第一个出现一次的数组
index = 0;
while(index != pString.length())
{
//注意,这里是对键值进行遍历,而不是从0开始到最后的值的遍历,也就是这里的循环只有pString.length()次
if(hashTable[pString.charAt(index)] == 1)
{
return pString.charAt(index);
}//if
++index;
}//while
return ' ';
}
@Test
public void test()
{
String s = "abaccdeff";
FirstNotRepeatingChar f = new FirstNotRepeatingChar();
System.out.println(f.firstNotRepeat(s));
}
}
【笔试】47、第一个只出现一次的字符
最新推荐文章于 2021-10-15 16:53:30 发布