[英]How do I count the number of unique characters in a string? - Updated
例如,字符串“abc”应该给出3个唯一字符,而字符串“abcccd”将给出4个唯一字符。 我不允许在这里使用Map,HashMap,TreeMap,Set,HashSet,StringBuffer或TreeSet。
到目前为止,我正在尝试使用for循环但是当我运行程序时,我一直得到0个独特的字符。 我是Java的新手,所以我真的不知道我在做什么。
编辑:所以我改变了代码,我得到了一个结果,但它最终比我想要的少1。 我将输入'abc',结果将显示为“2个唯一字符”而不是3个。 为了反击我在println语句中放置(uniqueChars + 1)。 这是一个很好的修正吗? 如果用户什么都不放,它仍然会说有1个唯一的字符。
更新的代码:
userText = userText.toLowerCase(); // userText is declared earlier in the program
// as the user's input. Setting this to lowercase
// so it doesn't say "a" and "A" are two different
// characters.
int uniqueChars = 0;
for (int i = 0; i < lengthText-1; i++) { // lengthText is declared earlier
// as userText.length();
if (userText.charAt(i) != userText.charAt(i+1))
uniqueChars++;
}
System.out.println("there are " + (uniqueChars + 1) + " unique characters in your string.");
}
这个怎么样? 它是一个正则表达式解决方案而不是循环:
public static int countUniqueCharacters(String input)
{
String unique = input.replaceAll("(.)(?=.*?\\1)", "");
return unique.length();
}
如果程序需要不区分大小写,则可以使用此代码:
public static int countUniqueCharacters(String input)
{
String unique = input.replaceAll("(?i)(.)(?=.*?\\1)", "");
return unique.length();
}
你可以使用return input.replaceAll(...).length();
.
匹配任何角色 (...)
创建一个捕获组,稍后将引用 (?=...)
创建一个前瞻,在输入中向前看 .*?
匹配角色及其匹配之间的任何内容(非贪婪匹配) \\\\1
匹配第一个捕获组 (?i)
设置不区分大小写的标志 因此,正则表达式将查找字符串中稍后有重复的任何字符,然后replaceAll
将用空字符串替换它。 因此,像"cabbacbdbadbcabdaadcb"
这样的输入变为"adcb"
(保留每个唯一字符的最后一个)。 然后,使用包含唯一字符的字符串,该字符串的长度就是答案。
如果由于某种原因,您需要唯一字符串并且您需要原始顺序,则必须在删除重复字符之前反转原始字符串(然后在完成后再将其反转)。 这将需要第三方库, StringBuffer
或循环。
这就是我想出的:
public static int countUniqueCharacters(String s) {
String lowerCase = s.toLowerCase();
char characters[] = lowerCase.toCharArray();
int countOfUniqueChars = s.length();
for (int i = 0; i < characters.length; i++) {
if (i != lowerCase.indexOf(characters[i])) {
countOfUniqueChars--;
}
}
return countOfUniqueChars;
}
我只检查每个字符的索引,如果它与原始索引不同,则会出现多次。
您可以创建一个名为uniqueChars
的新String
,并将其初始化为""
。 迭代你正在检查的String
的字符。 如果uniqueChars.contains(charToCheck)
为false
,则将该字符附加到uniqueChars
。 在循环结束时, uniqueChars.length()
将告诉您有多少个唯一字符。 这是丑陋和低效但它应该工作。
使用ArrayList
并添加一个charactar(如果不存在):
list = new ArrayList<String>();
for ( /* */ ) { // same for loop you wrote
String character = (String) text.charAt(i);
if(!list.contains(character)) { // note the '!'
list.add(character);
}
}
// and finally
int quantity = list.size();
以下是如何编写文件,如何读取同一文件以及重复特定字符的计数次数的程序:
package filereadexple;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
/*
* This is a program here I am creating a file by using "filewriter"
* and it is named as count.char and I am reading a same file and
* then how count number of times the particular character repeated.
*/
public class CountNoOfPartChar {
public static void main (String args[]){
File file = new File ("count.char");
try{
FileWriter fw = new FileWriter("count.char");
fw.write("In Xanadu did Kubla Khan");
fw.write("\r\n");
fw.write("A stately pleasure-dome decree:");
fw.write("\r\n");
fw.write("Where Alph, the sacred river, ran");
fw.write("\r\n");
fw.write("Through caverns measureless to man");
fw.write("\r\n");
fw.write("Down to a sunless sea.");
fw.close();
FileInputStream fis = new FileInputStream(file);
int i;
int occurs = 0;
char current;
while ((i=fis.available()) > 0){
current = (char)fis.read();
if(current == 'a'){
occurs++;
}
}
System.out.println("The number of particular character repeated is : " + occurs);
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
}
使用矢量。
char[] letters = new char[26];
for (char c : letters)
{
letters[c]=0;
}
然后对于找到的每个字母,增加向量中的位置。 如果任何条目的计数器大于1,那么您将重复
怎么样把它放入一个数组,按字母顺序排序,然后应用你的逻辑(比较邻接)?
v = sort(v);//your sort method
int count = 0;
for (int i = 0;i< lengthText-1; i++)
{ if v[i] == v[i + 1] {
i++;
} else {
count++;
}
}
顺便说一下,你的程序不起作用,因为你在你的for循环中做了i == lengthText-1
。
与@Alexandre Santos相同的逻辑,但使用工作示例代码。 复杂性是O(N)。 仅适用于不带空格,数字或特殊字符的字母字符串。
这也可以用作计数排序 。
public class CountChars
{
public static int countUniqCharacters(String str) {
int[] counts = new int['z' - 'a' + 1];
char[] arr = str.toLowerCase().toCharArray();
for (char c: arr) {
counts[c - 'a']++;
}
int unique = 0;
for (int i: counts) {
if (i > 0)
unique++;
}
return unique;
}
public static void main(String[] args) {
System.out.println("Unique char in " + args[0]
+ " is " + CountChars.countUniqCharacters(args[0]));
}
}
public class CharacterCount {
public static void main(String[] args) {
String s = "aaabbbcccddd";
String t="";
int count = 0;
//Loop to find unique characters in a string and add it to new string called t
//if a character is not found in a string indexOf returns -1
for (int i = 0; i < s.length(); i++) {
if (t.indexOf(s.charAt(i))==-1) t+=s.charAt(i);
}
//For every character new string t , loop though s find the count and display
for (int i = 0; i < t.length(); i++) {
count = 0;
for (int j = 0; j < s.length(); j++) {
if (t.charAt(i) == s.charAt(j)) count++;
}
System.out.println(t.charAt(i) + " " + count);
}
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
getvalues(s1);
}
public static void getvalues(String s1) {
String s2 = s1.toLowerCase();
StringBuffer sb = new StringBuffer(s2);
int l = sb.length();
int count = 0;
for (int i = 0; i < l; i++) {
count = 0;
for (int j = i + 1; j < l; j++) {
if (sb.charAt(i) == sb.charAt(j)) {
sb.deleteCharAt(j);
count++;
j--;
l--;
}
}
if (count > 0) {
sb.deleteCharAt(i);
i--;
l--;
}
}
if (sb.length() == 0) {
System.out.println(-1);
} else
System.out.println(sb.length());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.