Title description: Characters that appear only once
Find the first character that appears only once in the string s.
If not, return a single space. s contains only lowercase letters.
Achieve 1
/**
* @author apesource
*/
public class Program021 {
public static void main(String[] args) {
System.out.println(firstUniqChar("apesource")); //a
System.out.println(firstUniqChar("abbaccescdd")); //e
System.out.println(firstUniqChar("abbaccescdde")); //s
System.out.println(firstUniqChar("aabbg"));
}
/**
*
* @param s 原字符串
* @return 第一个只出现1次的字符,如果没有返回空格
*/
public static char firstUniqChar(String s) {
//遍历字符串s的前s.length()-2个字符
for(int i=0,len=s.length()-1;i<len;i++) {
//获取字符串的第1个字符
char c=s.charAt(0);
//截取第2个字符之后的元素
s=s.substring(1);
//判断当前字符是否为空
if(c==' ') {
//若为空,结束本轮循环
continue;
}
//判断截取的字符串中是否有该字符
if(!s.contains(String.valueOf(c))) {
//若没有该字符,说明该字符未重复,返回该字符
return c;
}else {
//若找到当前字符,说明有重复,将字符串中的该字符替换为空字符
s=s.replace(c, ' ');
}
}
//判断替换完之后,最后一个字符是否是空字符,如不是空字符,返回该字符
if(s.charAt(s.length()-1)!=' ') {
return s.charAt(s.length()-1);
}
//若是空字符,说明该字符串中的字符都有重复出现
return ' ';
}
Realization 2
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.Map.Entry;
/**
*
*
* @author apesource
*
*/
public class Program021 {
public static void main(String[] args) {
System.out.println(firstUniqChar("apesource")); //a
System.out.println(firstUniqChar("abbaccescdd")); //e
System.out.println(firstUniqChar("abbaccescdde")); //s
System.out.println(firstUniqChar("aabbg"));
}
/**
*
* @param s 原字符串
* @return 第一个只出现1次的字符,如果没有返回空格
*/
public static char firstUniqChar(String s) {
//创建集合,用于保存每个字符及个数
LinkedHashMap<Character, Integer> map=new LinkedHashMap<Character, Integer>();
//遍历字符串
for(int i=0;i<s.length();i++) {
//获取当前字符
char c=s.charAt(i);
//判断集合的键中是否存在当前字符
if(map.containsKey(c)) {
//如果存在,获取原值,加1后,重新存入
map.put(c, map.get(c)+1);
}else {
//如果不存在,添加至集合,值为1
map.put(c, 1);
}
}
//将Map中的所有键值对转换至Set集合,Set集合中的元素为Entry类型的对象(一个键值对)
Set<Entry<Character, Integer>> entrySet = map.entrySet();
//遍历set集合
for (Entry<Character, Integer> entry : entrySet) {
//如果当前键值对的值为1,返回该键值对的键
if(entry.getValue()==1) {
return entry.getKey();
}
}
//说明集合的值都不为1,字符串中的字符都有重复,返回空字符
return ' ';
}
Realize 3
/**
*
*
* @author apesource
*
*/
public class Program021 {
public static void main(String[] args) {
System.out.println(firstUniqChar("apesource")); //a
System.out.println(firstUniqChar("abbaccescdd")); //e
System.out.println(firstUniqChar("abbaccescdde")); //s
System.out.println(firstUniqChar("aabbg"));
}
/**
*
* @param s 原字符串
* @return 第一个只出现1次的字符,如果没有返回空格
*/
public static char firstUniqChar(String s) {
for(int i=0;i<s.length();i++) {
char c=s.charAt(i);
if(s.indexOf(c)==s.lastIndexOf(c)) {
return c;
}
}
return ' ';
}