Java 如何计算字符串中的唯一字符数更新
例如,字符串“abc”应给出3个唯一字符,而字符串“abcccd”应给出4个唯一字符。我不允许在这里使用Map、HashMap、TreeMap、Set、HashSet、StringBuffer或TreeSet 到目前为止,我试图使用for循环,但当我运行程序时,我总是得到0个唯一字符。我对Java有点陌生,所以我真的不知道自己在做什么 编辑:所以我改变了代码,得到了一个结果,但结果是比我想要的少了1。我将输入'abc',结果将显示为“2个唯一字符”,而不是3个。为了抵消这一点,我在println语句中添加了(uniqueChars+1)。这是一个好的修正吗?如果用户什么也不放,它仍然会说有一个唯一的字符 更新代码:Java 如何计算字符串中的唯一字符数更新,java,count,character,unique,Java,Count,Character,Unique,例如,字符串“abc”应给出3个唯一字符,而字符串“abcccd”应给出4个唯一字符。我不允许在这里使用Map、HashMap、TreeMap、Set、HashSet、StringBuffer或TreeSet 到目前为止,我试图使用for循环,但当我运行程序时,我总是得到0个唯一字符。我对Java有点陌生,所以我真的不知道自己在做什么 编辑:所以我改变了代码,得到了一个结果,但结果是比我想要的少了1。我将输入'abc',结果将显示为“2个唯一字符”,而不是3个。为了抵消这一点,我在println
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.");
}
userText=userText.toLowerCase();//userText在程序的前面声明
//作为用户的输入。将此设置为小写
//所以它没有说“a”和“a”是两个不同的词
//人物。
int uniqueChars=0;
对于(inti=0;i
您可以创建一个新的字符串,名为uniqueChars
,并将其初始化为”
。迭代您要检查的字符串中的字符。如果uniqueChars.contains(charToCheck)
为false
,则将该字符附加到uniqueChars
。在循环结束时,uniqueChars.length()
将告诉您有多少个唯一字符。这很难看,效率也很低,但它应该可以工作。使用向量
char[] letters = new char[26];
for (char c : letters)
{
letters[c]=0;
}
然后,对于找到的每个字母,增加向量中的位置。如果任何条目的计数器大于1,则您有重复项,将其放入数组,按字母顺序排序,然后应用您的逻辑(比较相邻项)
v=排序(v)//您的排序方法
整数计数=0;
对于(int i=0;i
顺便说一句,您的程序无法运行,因为您在for循环中执行了i==lengthText-1
。这就是我想到的:
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;
}
public static int countUniqueCharacters(字符串s){
String lowerCase=s.toLowerCase();
字符[]=小写。toCharArray();
int countOfUniqueChars=s.length();
for(int i=0;i
我只是检查每个字符的索引,如果它与原始索引不同,就会出现多次 使用ArrayList
,如果尚未在其中添加字符,则添加字符:
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();
list=newarraylist();
对于(/**/){//,与您编写的循环相同
String character=(String)text.charAt(i);
如果(!list.contains(character)){//请注意“!”
列表。添加(字符);
}
}
//最后
int数量=list.size();
这个怎么样?这是一个正则表达式解决方案,而不是一个循环:
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();
}
您可以使用返回input.replaceAll(…).length()使其成为一个单行方法代码>
Regex解释说:
匹配任何字符
(…)
创建一个捕获组,供以后引用
(?=…)
创建一个向前看,以便在输入中向前看
*?
匹配字符与其匹配项之间的任何内容(非贪婪匹配)
\\1
匹配第一个捕获组
(?i)
设置不区分大小写的标志
因此,正则表达式将查找任何稍后在字符串中有重复项的字符,然后replaceAll
将用空字符串替换它。因此,像“cabbabbdbadbcbabdaadcb”
这样的输入变成“adcb”
(保留每个唯一字符的最后一个)。然后,对于包含唯一字符的字符串,该字符串的长度就是答案
如果出于某种原因,您需要唯一的字符串,并且需要按原始顺序使用它,则必须先反转原始字符串,然后再剥离重复的字符(完成后再反转)。这需要一个第三方库,StringBuffer
,或者一个循环。与@Alexandre Santos的逻辑相同,但使用的是工作示例代码。复杂性是O(N)。
仅适用于不带空格、数字或特殊字符的字母字符串
这也可以用作
以下是如何写入文件、如何读取同一文件以及如何计算特定字符重复次数的程序:
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());
}
}
}
公共类字符计数{
公共静态void main(字符串[]args){
字符串s=“aaabbbccddd”;
字符串t=“”;
整数计数=0;
//循环以查找字符串中的唯一字符,并将其添加到名为t的新字符串中
//如果在字符串中找不到字符,indexOf返回-1
对于(int i=0;ipublic 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]));
}
}
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());
}
}
}
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());
}
}