剑指offer:第一个只出现一次的字符位置
来源:互联网 发布:怎么查看淘宝店家电话 编辑:程序博客网 时间:2024/06/04 19:47
题目描述
在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置
双重循环遍历,暴力求解
双重for循环遍历,将两个一样的值赋为'$',最后在原串中找出第一个非'$'的字符
public class Solution { public int FirstNotRepeatingChar(String str) { int flag=-1; int length=str.length(); if(length<=0) return -1; if(length>=1&&length<=1000){ char [] ch=str.toCharArray(); for(int i=0;i<length;i++){ char wechar=ch[i]; for(int j=0;j<length;j++){ if(wechar==ch[j]&&(i!=j)){ ch[i]='$'; ch[j]='$'; } } } for(int i=0;i<length;i++){ if(ch[i]!='$'){ flag=i; break; } } } return flag; }}
数组下标唯一性
将字符作为数组的下标,放进arr数组中,将下标所对应的值++操作,最后找出只出现一次的那个数(感觉有bug,但是在牛客平台能编译通过)
public class Solution { public int FirstNotRepeatingChar(String str) { int arr[]=new int[128]; for(int i=0;i<str.length();i++){ arr[str.charAt(i)]++; } for(int i=0;i<str.length();i++){ if(arr[str.charAt(i)]==1){ return i; } } return -1; }}
利用HashMap的containsKey()方法
import java.util.*;public class Solution { public int FirstNotRepeatingChar(String str) { HashMap<Character,Integer> map=new HashMap<Character,Integer>(); for(int i=0;i<str.length();i++){ char ch=str.charAt(i); if(map.containsKey(ch)){ int time=map.get(ch); time++; map.put(ch,time); }else{ map.put(ch,1); } } for(int i=0;i<str.length();i++){ if(map.get(str.charAt(i))==1) return i; } return -1; }}
阅读全文
0 0
- 《剑指offer》第一个只出现一次的字符位置
- 剑指offer:第一个只出现一次的字符位置
- 剑指Offer--第一个只出现一次的字符位置
- 【剑指Offer】第一个只出现一次的字符位置
- 剑指offer:第一个只出现一次的字符位置
- [剑指offer]第一个只出现一次的字符位置
- 《剑指offer》-第一个只出现一次的字符位置
- 剑指offer|第一个只出现一次的字符位置
- 【剑指Offer】第一个只出现一次的字符位置
- 剑指offer:第一个只出现一次的字符位置
- 第一个 只出现一次的字符 位置(剑指offer)+哈希
- 剑指offer—第一个只出现一次的字符位置
- 《剑指offer》——第一个只出现一次的字符位置
- 码农小汪-剑指Offer之32 -第一个只出现一次的字符位置
- 剑指offer 34 第一个只出现一次的字符位置
- 剑指Offer--035-第一个只出现一次的字符位置
- 剑指offer(三十八)之第一个只出现一次的字符位置
- 剑指offer(31)-第一个只出现一次的字符位置
- 配置samba服务--centos7.x
- 软件JDK的安装及变量参数设置
- Hadoop单机安装-yellowcong
- XML_Dom4j的使用
- Linux下的虚拟串口驱动(三)
- 剑指offer:第一个只出现一次的字符位置
- 任总在新员工入职培训座谈会上的讲话
- Android hybrid 开发实践(android webview)
- 码位(code position/point)Unicode 编码与 Python 2/3 编码兼容性问题
- 【Java】EL表达式
- RecyclerView回收原理分析
- 设计模式(五)--装饰模式
- 二分图最大匹配(HihoCoder
- echarts资源