当前位置:编程学习 > JAVA >>

求解

java编程题:输入一个字符串,统计这个字符串中有几个不重复的字符? Java 编程 --------------------编程问答-------------------- 你想干嘛? --------------------编程问答--------------------
public class RepeatChar {

public static void main(String[] args) {
//键盘输入字符串
System.out.print("请输入待测试的字符串:");
Scanner sc = new Scanner(System.in);
//得到字符串
String str = sc.nextLine();

//若str为空,则什么都不做
if(null == str || 0==str.length())
{
System.out.println("请不要输入空字符串!");
return;
}

//生成字符数组
char[] strArray = str.toCharArray();

//存放不重复字符的list
List<Character> strList = new ArrayList<Character>();
//存放重复字符的list
List<Character> repeatList = new ArrayList<Character>();

//循环处理字符数组
for(char c : strArray)
{
//若在重复列表中存在,则跳过此次循环
if(repeatList.contains(c))
{
continue;
}

//若在不重复列表中存在,则需要剔除此字符
if(strList.contains(c))
{
repeatList.add(c);
strList.remove(Character.valueOf(c));
}
else
{
//不存在则加入不重复列表
strList.add(c);
}
}

System.out.println("不重复的字符有"+strList.size()+"个:"+strList);
}
}
--------------------编程问答--------------------
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

public class CharacterStatistic {
public static void main(String[] args) throws UnsupportedEncodingException{
String str = readString5("请输入字符串:");
statistic(str);
//System.out.println("readString5 方法的输入:" + str);
}

private static void statistic(String str) throws UnsupportedEncodingException {
byte[] bytes = str.getBytes();
Map<Byte, Integer> map = new HashMap<Byte,Integer>();
for (int i = 0; i < str.length(); i++) {
//System.out.println((char)bytes[i]);
byte a = bytes[i];
if (map.containsKey(a)) {
//System.out.println("a1:" + a);
map.put(a, (map.get(a)+1));
} else {
//System.out.println("a2:" + a);
map.put(a, 1);
}
}
int cnt = 0;
Set<Entry<Byte, Integer>> set = map.entrySet();
Iterator<Entry<Byte, Integer>> it = set.iterator();
while (it.hasNext()) {
Entry<Byte, Integer> entry = it.next();
byte key = entry.getKey();
int value = entry.getValue();
System.out.print("key:" + key + ", value:" + value + "\n");
if (entry.getValue() <= 1) {
//System.out.print(entry.getKey() + ",");
cnt++;
}
}
System.out.println("\ncnt: " + cnt);
}

private static String readString5(String prompt) {
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}

}


昨晚上本来写了一下代码的,但是有点小问题,有点急回家了,刚到公司稍微改了一下,基本上能用。上面的程序只能识别纯的ascii码,碰到中文字符的时候,统计会有问题。
程序也基本没考虑性能的问题,应该有很大的改善空间 --------------------编程问答--------------------
引用 楼主 u010856321 的回复:
java编程题:输入一个字符串,统计这个字符串中有几个不重复的字符?


这个可以使用API不?
如果可以使用的话用HashSet分分钟的事!
补充:Java ,  Java相关
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,