[英]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.