您的位置:首页 > 其它

String——第一个只出现一次的字符

2016-05-12 16:01 218 查看
题目一:字符串中第一个只出现一次的字符

方法:判断字符串字频,用hashmap

public int FirstNotRepeatingChar(String str) {
if(str == null||str.length()==0)
return -1;
int []count=new int[256];
for(int i=0;i<str.length();i++)
{
count[str.charAt(i)]++;
}

for(int i=0;i<str.length();i++)
{
if(count[str.charAt(i)]==1)
return i;
}
return -1;
}


题目二:字符流中第一个只出现一次的字符

方法:与String不同的地方是,需要用一个ArrayList将字符流中的字符全部保存下来。

import java.util.*;
public class Solution {
//Insert one char from stringstream
ArrayList<Character> list=new ArrayList();
HashMap<Character,Integer> map=new HashMap();

public void Insert(char ch)
{
list.add(ch);
if(map.get(ch) == null)
{
map.put(ch,1);
}else
{
map.put(ch,map.get(ch)+1);
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
if(list.size() == 0)
return '#';
for(int i=0;i<list.size();i++)
{
if(map.get(list.get(i)) == 1)
{
return list.get(i);
}
}
return '#';
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: