String——第一个只出现一次的字符
2016-05-12 16:01
218 查看
题目一:字符串中第一个只出现一次的字符
方法:判断字符串字频,用hashmap
题目二:字符流中第一个只出现一次的字符
方法:与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 '#';
}
}
方法:判断字符串字频,用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 '#';
}
}
相关文章推荐
- 一个10年的程序员的感叹!
- NT内核代码分析
- ReactOS实现的兼容NT内核分析--KfLowerIrql函数
- 简单的使用NPOI读取和生成Excel文件
- 第十二周上机实践项目-项目1-(2)-阅读程序
- @font-face的用法
- 微信分享JS-SDK示例页面
- myeclipse自定义代码风格
- Table of Contents - JMS
- Table 'performance_schema.session_variables' doesn't exist
- MYSQL的随机查询的实现方法
- Docker容器的数据管理
- ffmpeg常用命令
- osg粒子
- 解决Django生成csv乱码问题
- ALAsset,ALAssetsLibrary,ALAssetsgroup常见属性及用法
- at org.apache.hadoop.util.RunJar.main(RunJar.java:153)
- String和StringBuilder的区别
- 详细解析Dynamo存储引擎
- 文件上传下载