Count of distinct duplicated characters in Java - java

I've written code to find the amount of duplicated characters in a string input. However after reading the specification, I realise this isn't what is being asked. Yes, I need to count the duplicated characters, but not the amount of that particular character, I need the amount of all characters being duplicated.
I've given an input and output to help explain better. I don't think I'm doing a good job.
Input:
"abcdea" => "a" is duplicated =>
Output:
1
Input:
"abcdeae" => "a" and "e" is duplicated =>
Output:
2
Input:
"abcdeaed" => "a", "d" and "e" is duplicated =>
Output:
3
I've put my code below. Can anyone help adjust my code please?
public static int duplicatesCount(String text)
{
Map<Character,Integer> map = new HashMap<Character,Integer>();
char[] carray = text.toCharArray();
for (char c : carray)
{
if (map.containsKey(c))
{
map.put(c, map.get(c) +1);
}
else
{
map.put(c, 1);
}
}
Set <Character> setChar = map.keySet();
int returnC = 1;
for (Character c : setChar)
{
if (map.get(c) > 1)
{
returnC = map.get(c);
}
}
return returnC;

A better way to do this is to sort the string and then iterate through it. If the previous character = the current character, you increase the duplicate number and don't increment it again util you see the character change.
This requires no extra storage (e.g. the hash map).
This can also be used to count the number of duplicates of each letter with a minor change :).

At the end of your snippet...
int returnC = 0;
for (Character c : setChar)
{
if (map.get(c) > 1)
{
returnC ++; //for each which has more than one instance
}
}
return returnC;

Just count everytime you come across a character that has a value greater than 1 in your hashmap
int returnC = 0;
for (Character c : setChar)
{
if (map.get(c) > 1)
returnC++;
}
Or you can do it while you're creating your hashmap like this
Map<Character,Integer> map = new HashMap<Character,Integer>();
char[] carray = text.toCharArray();
Set <Character> setChar = new Set<Character>(); //initialize the set up here
for (char c : carray)
{
if (map.containsKey(c))
{
map.put(c, map.get(c) +1);
setChar.add(c); //just add to set when a char already exists
}
else
{
map.put(c, 1);
}
}
return setChar.size(); //then simply return the size of the set

Here is another approach - without using Map or sorting algorithm.
public static int duplicatesCount(String text) {
int cnt = 0;
while (text.length() > 1) {
char firstLetter = text.charAt(0);
if (text.lastIndexOf(firstLetter) > 0) {
cnt++;
text = text.replaceAll(("" + firstLetter), "");
} else {
text = text.substring(1, text.length());
}
}
return cnt;
}
The basic idea is to go through a string, char-by-char and check does the character exist somewhere in the string ( if (text.lastIndexOf(firstLetter) > 0)). If it exists increment cnt and then remove all occurrences of the character in the string.
Otherwise, just remove the fist character (text = text.substring(1, text.length());)

You could use String methods
int count = 0;
String s = "abcdeabc";
while(s.length() > 0) {
String c = s.substring(0, 1);
if(s.lastIndexOf(c) != 0) {
count++;
}
s = s.replaceAll(c, "");
}

In your current code you are returning the value not the count.
For Eg:
If your input was "abcdea", then returnC holds the value 2 which is the
number of times the key a has repeated.
If your input was "abcdabeb" where a is repeated twice and b is repeated
thrice. Your output will be 3, as returnC will be holding the value for the key
b.
You can modify your code like this.
Set <Character> setChar = map.keySet();
int returnC = 0;
for (Character c : setChar) {
if (map.get(c) > 1) {
returnC++;
}
}
return returnC;

Also we can user String Buffer class to to create another string of duplicate charracters-- and then we can display it--
public static void main(String arghya[])
{
String name="ARGHYA MUKHERJEE";
StringBuffer duplicate=new StringBuffer();
Set<Character> charlist=new HashSet<Character>();
for(int i=0;i<name.length();i++) {
Character c=name.charAt(i);
if(charlist.contains(c))
{
duplicate.append(c);
//System.out.println(c+ " is repeatitive character in the string");
}
else {
charlist.add(c);
}
}
System.out.print("Duplicate characters which has appeared are as follows: "+duplicate);
}

Related

First non-repeating character in a stream of characters

The question asks us to find new string B.
B is formed such that we have to find first non-repeating character each time a character is inserted to the stream and append it at the end to B. If no non-repeating character is found then append '#' at the end of B.
Example:
"a" - first non repeating character 'a'
"ab" - first non repeating character 'a'
"aba" - first non repeating character 'b'
"abad" - first non repeating character 'b'
"abadb" - first non repeating character 'd'
"abadbc" - first non repeating character 'd'
Can someone help me out where my code went wrong. my logic is to use substring function of string and find the unique character and add it to arraylist and print the entire arraylist.
public class Solution
{
public String solve(String A)
{
ArrayList<Character>a=new ArrayList<Character>();
String res="";
for(int i=0;i<A.length();i++)
{
String ss=A.substring(0,i+1);
String ue=uniqueCharacters(ss);
// System.out.println(ue);
if(ue!="") a.add(ue.charAt(0));
else a.add('#');
}
for(Character j:a) res+=j;
return res;
}
public static String uniqueCharacters(String test)
{
String temp = "";
for (int i = 0; i < test.length(); i++)
{
char current = test.charAt(i);
if (temp.indexOf(current) < 0) temp = temp + current;
else temp = temp.replace(String.valueOf(current), "");
}
return temp;
}
}
It may be better to use a Set to detect unique characters in the input string using the result of Set::add which returns false if no element has been actually added to the set, and a Queue to maintain the non-repeated characters.
When a repeated (non-unique) character is detected, it gets removed from the queue and if necessary, "#" is applied as a placeholder. And if a unique character is detected, it is just added to the queue.
Example implementation:
public static String solve(String str) {
// verify the input
if (null == str || str.isEmpty()) {
return str;
}
Set<Character> previous = new LinkedHashSet<>();
Queue<Character> nonRepeated = new LinkedList<>();
StringBuilder sb = new StringBuilder();
// use the first character
char curr = str.charAt(0);
previous.add(curr);
nonRepeated.add(curr);
sb.append(curr);
for (int i = 1, n = str.length(); i < n; i++) {
char c = str.charAt(i);
if (!previous.add(c)) { // duplicate character found
nonRepeated.remove(c);
if (nonRepeated.isEmpty()) {
curr = '#';
} else { // get the next non-repeated character
curr = nonRepeated.peek();
}
} else { // unique element is detected
if (curr == '#') {
curr = c;
}
nonRepeated.add(c);
}
sb.append(curr);
}
return sb.toString();
}
Tests:
for (String t : Arrays.asList("abadbc", "abcdba", "aaabbbacab")) {
System.out.printf("input: %s --> %s%n----%n", t, solve(t));
}
Output:
input: abadbc --> aabbdd
----
input: abcdba --> aaaaac
----
input: aaabbbacab --> a##b###ccc
----
When you encounter a char a 2nd time you remove it from the unique characters (1), but if there was a 3rd of that character it would be added again (2).
public static String uniqueCharacters(String test)
{
String temp = "";
for (int i = 0; i < test.length(); i++)
{
char current = test.charAt(i);
if (temp.indexOf(current) < 0) temp = temp + current; <---- (2)
else temp = temp.replace(String.valueOf(current), ""); <----- (1)
}
return temp;
}
Solution count the number of chars and then return only those whose count is 1 (one).

Why the following could determine if str1 and str2 are anagram?

I am reading a code snippet and I am wondering why the following could
check if str1 and str2 are anagram.
boolean result = str1.chars().allMatch( c1 -> str2.chars()
.anyMatch( c2 -> c1 == c2) );
I am particularly confused about
if str1 = "abc" str2 = "cbad", the result should be also true, right?
I am particularly confused about if str1 = "abc" str2 = "cbad", the result should be also true, right?
The code will return true, yes. So no, it's not a valid check for an anagram, since in the example you cite, it will say it's an anagram when it's not (since str1 doesn't have d).
In an anagram, both strings would need to have the same number of occurrences of the same letters. One byproduct of that is that they would need to be the same length (although in some anagram schemes, you're allowed to vary the number of spaces and add/remove punctuation).
So a valid check would need to ensure that every character in str1 (perhaps ignoring spaces and punctuation) consumed a character from str2, and that there were no characters from str2 left at the end (perhaps ignoring spaces and punctuation). There are lots of ways to do that (count the occurrences in str1, perhaps in a Map, and then count down matches from str2; have a string you remove letters from, etc.) The quoted code just isn't one of them.
If you have str1 = "abc" and str2 = "cbad", they cannot be anagram of each other because str2 contains the extra character d which str1 does not have. For one word to be an anagram of the other word, they each needs to have the same character with the same number of frequencies.
That being said, I just ran the code you have written and it does not work for that specific case that you have mentioned.
One way you can determine if one string is an anagram of another string is by using two HashMap. For each strings, loop through it, track each character as the key and its frequencies as value. At the end, you can loop through both of the HashMap and keep comparing the value for each key. If the values are not equal, return false.
Also first thing to check is that the length of both strings should be equal. If they fail that condition, they cannot be an anagram then.
The following is the code I wrote on LeetCode many months ago. This can definitely be optimized and made much more cleaner but just to give you an idea.
public class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
HashMap<Character, Integer> tmap = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
int count = map.get(c);
map.put(c, count + 1);
}
else {
map.put(c, 1);
}
}
for (int j = 0; j < t.length(); j++) {
char d = t.charAt(j);
if (!(map.containsKey(d))) {
return false;
}
if (tmap.containsKey(d)) {
int tracker = tmap.get(d);
tmap.put(d, tracker + 1);
}
else {
tmap.put(d, 1);
}
}
for (Character key: map.keySet()) {
int mapv = map.get(key);
int tmapv = tmap.get(key);
if (mapv != tmapv) {
System.out.println(tmapv);
System.out.println(mapv);
return false;
}
}
return true;
}
}
Based on T.J. Crowder's answer this should be a possible way to check for an anagram:
public static boolean isAnagram(String subject, String possibleAnagram, IntPredicate isAnagramCodePoint)
{
Objects.requireNonNull(subject);
Objects.requireNonNull(possibleAnagram);
Objects.requireNonNull(isAnagramCodePoint);
// Convert inputs to valid anagram letters.
int[] subjectLetters = subject.codePoints()
.filter(isAnagramCodePoint)
.toArray();
int[] possibleAnagramLetters = possibleAnagram.codePoints()
.filter(isAnagramCodePoint)
.toArray();
// Permutation = Same number of occurrences of the same letter.
if (subjectLetters.length != possibleAnagramLetters.length)
{
return false;
}
HashMap<Integer, Integer> occurrences = new HashMap<>(subjectLetters.length);
// Count (produce) number of occurrences for each letter in subject.
for (int codePoint : subjectLetters)
{
occurrences.merge(codePoint, 1, (a, b) -> a + b);
}
// Consume each letter occurrence from subjectLetters.
for (int codePoint : possibleAnagramLetters)
{
int val = occurrences.merge(codePoint, -1, (a, b) -> a + b);
if (val == -1)
{
return false; // Current letter occurred more often in possibleAnagram
}
}
// Check equal number of occurrences for the same letter.
for (int number : occurrences.values())
{
if (number != 0)
{
return false;
}
}
return true;
}
private static final IntPredicate COMPLETE = (codePoint) -> true;
public static boolean isAnagram(String subject, String possibleAnagram)
{
return isAnagram(subject, possibleAnagram, COMPLETE);
}
The optional IntPredicate is used to specify the anagram schema, a possible value could be Character::isLetter to ignore all code points except letters, Character::isDigit, etc.

How to find anagram for 2 Strings

I have written a Java program to find Anagram for 2 strings.
For Reference:
Two strings are anagrams if they are written using the same exact letters, ignoring space, punctuation and capitalization. Each letter should have the same count in both strings. For example, Army and Mary are anagram of each other.
Program:
package practice;
import java.util.ArrayList;
import java.util.List;
public class Anagram_String {
public static void main(String[] args) {
String s1="mary";
String s2="army";
int k=0;
List<String> matchedChar= new ArrayList<String>();
String charmatch="";
char[] ch1= s1.toLowerCase().toCharArray();
char[] ch2= s2.toLowerCase().toCharArray();
if(s1.length()==s2.length())
{
for(int i=0;i<s1.length();i++)
{
for(int j=0;j<s2.length();j++)
{
if(ch1[i]==ch2[j])
{
k++;
charmatch=String.valueOf(ch1[i]);
System.out.println(charmatch);
matchedChar.add(charmatch);
System.out.println("Arraylist value is "+matchedChar.toString());
System.out.println(matchedChar.size());
}
}
k=0;
}
String arrayValue=matchedChar.toString();
System.out.println("Array value is "+arrayValue);
if(arrayValue.contains(s2)){
System.out.println("String 1 and String 2 are anagrams of each other");
}
else
{
System.out.println("String 1 and String 2 are not anagrams of each other");
}
}
}
}
Output:
m
Arraylist value is [m]
1
a
Arraylist value is [m, a]
2
r
Arraylist value is [m, a, r]
3
y
Arraylist value is [m, a, r, y]
4
Array value is [m, a, r, y]
String 1 and String 2 are not anagrams of each other
Here if you see all the characters are added to to the arraylist but when compared with the string, it is showing the output as they are not anagrams of each other.
Kindly help me to find solution for this.
Thank you,
What I think is that your solution will work only for words with unique characters, and time complexity will be O(n^2) (where n - is the length of String).
However, there is a better solution for such problem:
Take String.toCharArray() value for each string
Sort those arrays
If those arrays are equal, then your words are anagrams
You can count number of letters in both strings. If both strings have the same number of letters they are anagrams.
You can use an int[] to store number of letters.
public static boolean anagrams(String a, String b) {
int[] letters = new int[26];
// Convert to upper case because the test is case insensitive
a = a.toUpperCase();
b = b.toUpperCase();
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
if (ch < 'A' || ch > 'Z') {
continue; // Skip non letters
}
letters[ch - 'A']++; // Increment number of the current letter
}
for (int i = 0; i < b.length(); i++) {
char ch = b.charAt(i);
if (ch < 'A' || ch > 'Z') {
continue; // Skip non letters
}
letters[ch - 'A']--; // Decrement number of the current letter
}
for (int i = 0; i < letters.length; i++) {
if (letters[i] != 0) {
// If there are more or less of this letter
// in the first string it is not an anagram
return false;
}
}
return true;
}
Note this algorithm is done in O(n) where n is the number of letters of each string. Sorting the strings needs at least O(n log(n))
Taking the idea from AxelH's comments it is possible to create an external method to loop as follow.
private void countLetters(int[] letters, String str, int incrementFactor) {
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch < 'A' || ch > 'Z') {
continue; // Skip non letters
}
letters[ch - 'A'] += incrementFactor;
}
}
public static boolean anagrams(String a, String b) {
int[] letters = new int[26];
countLetters(letters, a.toUpperCase(), 1); // Note the +1
countLetters(letters, b.toUpperCase(), -1); // Note the -1
for (int i = 0; i < letters.length; i++) {
if (letters[i] != 0) {
// If there are more or less of this letter
// in the first string it is not an anagram
return false;
}
}
return true;
}
This seems to me a more readable and elegant way. Thanks AxelH.
Note In the previous code there are expressions like letters[ch - 'A']++. This line of code use an interesting properties of type char of java that is a special primitive numeric type, so it is possible to use mathematical operations on it.
In particular:
'A' - 'A' --> 0
'B' - 'A' --> 1
'C' - 'A' --> 2
'D' - 'A' --> 3
...
'Z' - 'A' --> 25
So this expression can be used to give an index to a letter starting from 0 for A ending to 25 for Z.
My answer is quite similar to Marine's, but takes a little higher-level approach with Java 8 streams, making the code a little more concise and readable:
public class Application {
public boolean isAnagramsEqual(String str1, String str2) {
Map<Character, Long> count = countChars(str1);
Map<Character, Long> count2 = countChars(str2);
return count.equals(count2);
}
private Map<Character, Long> countChars(String str) {
return str.toLowerCase()
.chars().mapToObj(ch -> (char) ch) //convert into stream of Characters
.filter(Character::isLetterOrDigit) //filter out not-needed chars
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}}
Method countChars creates a map with each unique character mapped to it's count in the given string.
It may be a little less performant than Marine's, but it's still O(n).
Your outputs says it itself:
Array value is [m, a, r, y]
As mentioned above I would also just create array and sort them, but here is the solution you may be searching for:
String s1="mary";
String s2="army";
List<String> matchedChar= new ArrayList<String>();
String charmatch="";
char[] ch1= s1.toLowerCase().toCharArray();
char[] ch2= s2.toLowerCase().toCharArray();
if(s1.length()==s2.length())
{
for(int i=0;i<s1.length();i++)
{
for(int j=0;j<s2.length();j++)
{
if(ch1[i]==ch2[j])
{
charmatch=String.valueOf(ch1[i]);
System.out.println(charmatch);
matchedChar.add(charmatch);
System.out.println("Arraylist value is "+matchedChar.toString());
System.out.println(matchedChar.size());
}
}
}
String arrayValue="";
for (String s : matchedChar){
arrayValue = arrayValue + s;
}
System.out.println("Array value is "+arrayValue);
System.out.println("s1 value is "+s1);
if(arrayValue.equals(s1)){
System.out.println("String 1 and String 2 are anagrams of each other");
}
else
{
System.out.println("String 1 and String 2 are not anagrams of each other");
}
}
Use .split("(?!^)") on your String to make it an String Array. Next sort arrays and compare it. It's the best option for me too.
This is how you can do it by sorting the arrays:
public static void main(String[] args) {
System.out.println(isAnagram("mary", "army"));
}
public static boolean isAnagram(String s1, String s2){
char[] c1 = s1.toLowerCase().toCharArray();
char[] c2 = s2.toLowerCase().toCharArray();
Arrays.sort(c1);
Arrays.sort(c2);
boolean anagram = false;
if(Arrays.equals(c1, c2)){anagram = true;}
return anagram;
}
In this code i converted my string into char array using the code :String.toCharArray() inside a function named toSort() and sorted the words in the string. Then inside Isanagram() method I checked whether it is anagram or not. For that first I have to make sure whether the sorted strings are of same length or not after I compared each character in one string with other.
Here is the full code try to decompose each method and study.
import java.util.Scanner;
public class StANaEx1 {
String toSort(String s5){
int i,j;
char temp;
char ch1[] = s5.toCharArray();
int len = ch1.length;
for(i=0;i<len;i++){
for(j=i+1;j<len;j++){
if(ch1[i]>ch1[j]){
temp = ch1[i];
ch1[i] = ch1[j];
ch1[j] = temp;
}
}
}
String s6 = new String(ch1);
return s6;
}
void isAnagram(String s9,String s10){
int i,len1,len2,flag=0;
System.out.println("s9 : "+s9);
System.out.println("s10 : "+s10);
System.out.println("");
s9 = s9.trim(); //To remove white spaces again no need.I used because my compiler didn't recognize my replace() method in main() method.
s10 = s10.trim();
len1 = s9.length();
len2 = s10.length();
System.out.println("len1 : "+len1); //To check the length of the given strings without white spaces.
System.out.println("len2 : "+len2);
System.out.println("");
for(i=0;i<len1;i++){
System.out.println("s9["+i+"] : "+s9.charAt(i)); //Error checking.
}
System.out.println("");
for(i=0;i<len2;i++){
System.out.println("s10["+i+"] : "+s10.charAt(i));
}
System.out.println("");
if(len1!=len2){
System.out.println("Not Anagram string length different");
}
else{
for(i=0;i<len1;i++){ //Since string lengths are same len1 = len2.
if(s9.charAt(i)!=s10.charAt(i)){
flag=1;
break;
}
}
if(flag==0){
System.out.println("Anagram");
}
else{
System.out.println("Not Anagram");
}
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
StANaEx1 ob1 = new StANaEx1();
System.out.println("-----Anagram checking-----");
System.out.println("");
System.out.println("Enter the 1st String: ");
System.out.println("");
String s1 = sc.nextLine();
s1 = s1.replace("//s", ""); //This is to remove white spaces.
String s3 = s1.toLowerCase(); //Change the input string to lower case in order to make sorting easy.
System.out.println("");
System.out.println("Enter the next String: ");
String s2 = sc.nextLine();
s2 = s2.replace("//s", "");
String s4 = s2.toLowerCase();
System.out.println("");
String s7 = ob1.toSort(s3);
String s8 = ob1.toSort(s4);
ob1.isAnagram(s7,s8);
sc.close();
}
}
Output
-----Anagram checking-----
Enter the 1st String:
Mary
Enter the next String:
army
s9 : amry
s10 : amry
len1 : 4
len2 : 4
s9[0] : a
s9[1] : m
s9[2] : r
s9[3] : y
s10[0] : a
s10[1] : m
s10[2] : r
s10[3] : y
Anagram
Output 2
-----Anagram checking-----
Enter the 1st String:
Sniper
Enter the next String:
kill
s9 : einprs
s10 : ikll
len1 : 6
len2 : 4
s9[0] : e
s9[1] : i
s9[2] : n
s9[3] : p
s9[4] : r
s9[5] : s
s10[0] : i
s10[1] : k
s10[2] : l
s10[3] : l
Not Anagram string length different
import java.util.Arrays;
public class AnagramString {
public static void main(String[] args) {
String str1="Keep";
String str2="peek";
//convert the string into the array with lower casing its character
char arrstr1[]=str1.toLowerCase().toCharArray();
char arrstr2[]=str2.toLowerCase().toCharArray();
//sort the array of character by acending order
Arrays.sort(arrstr1);
Arrays.sort(arrstr2);
//set true boolean value to the status
boolean status=true;
//comparing the char array
status = Arrays.equals(arrstr1, arrstr2);//here we get true value if they are containing the same character
System.out.println(Arrays.toString(arrstr1));
System.out.println(Arrays.toString(arrstr2));
if(arrstr1.length==arrstr2.length && status) {
System.out.println("2 string are anagram");
}else {
System.out.println("2 string are not anagram");
}
}
}

Find if a string is unique or not

I want to use hashtable to find unique characters as it seems more efficient to me so for example, hello in hashtable would be=> {h:1,e:1,l:2,o:1} & since value is more than 1 then string isnt unique. I know I can do ascii way of counting unique characters but I want to implement the hashtable way.
Please note, I do not want a regex implementation.
static void findHashUnique(String str)
{
Hashtable<Character, Integer> ht = new Hashtable<Character, Integer>();
for(int i=0;i<str.length();i++)
{
int cnt=1;
if(!ht.containsKey(str.charAt(i)))
{
ht.put(str.charAt(i), cnt);
}
}
System.out.print(ht);
}
I am stuck at the part of how will I first initialize the hashtable & also check if value exists then increment. In case of 'l' it will increment to 2 instead of being 1 since the key is the same.
Also Is this solution efficient?
Here's my approach.
String string = "hello";
Hashtable<Character, Integer> map = new Hashtable<>();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
System.out.println(map);
Output: {e=1, o=1, l=2, h=1}
Well, I don't know exactly what character encodings you will be examining, but if you are constraining yourself to only ASCII characters, you can use a simple array of 128 elements.
public static String uniqueLetters(String s) {
// storage for ascii characters
char[] letters = new char[128];
// mark counts of all letters
for(int i = 0; i < s.length(); i++) {
letters[ (int)s.charAt(i) ]++;
}
// find unique letters
String uniques = "";
for(int i = 0; i < letters.length; i++) {
if ( letters[i] == 1 ) {
uniques += Character.toString( (char)letters[i] );
}
}
return uniques;
}
To "fix" your code, use a HashSet<Character>, which uses a Hashtable internally, but you don't have to know or worry about that. Just keep adding the chars to the set and you'll be left with a unique set of chars at the end.
To achieve the intention more easily:
String uniqueChars = str.replaceAll("(.)(?=.*\\1)", "");

How can I check character occurrence in a string?

My Question is-
Input is string. Return true if the String has exactly 1 character that appears twice in the string, 0 character that appear thrice in the string, and at least 1 character that appear four or more times in the string. There is a problem in my code and I am unable to find out the problem.
public class CheckCharacterOccurence {
static String testcase1 = "jjiiiiyy";
public static void main(String[] args) {
CheckCharacterOccurence testInstance = new CheckCharacterOccurence();
boolean result = testInstance.checkCharacterOccurence(testcase1);
System.out.println(result);
}
public boolean checkCharacterOccurence(String str) {
char ch=' ';
char ch1=' ';
int temp=0;
int temp1=0;
int temp2=0;
int count=0;
for(int i=0;i<str.length();i++){
ch=str.charAt(i);
for(int j=i;j<str.length();j++){
if(str.charAt(i)==str.charAt(j)){
ch1=str.charAt(i);
count++;
}
}
System.out.println(count);
if(count==2&&ch!=ch1){
temp++;
}
if(count==3&&ch!=ch1){
temp1++;
}
if(count>=4){
temp2++;
}
count=0;
}
if(temp==1&&temp1==0&&temp2>=1){
return true;
}
return false;
}
}
I would suggest using a map
For all characters in string, increment map[that_char]
At last iterate over map to find how many times each character appeared.
Alternatively you can use array also to keep count.
Something like
int [] ctr = new int[256]
ctr = all zeroes
for (ch : string)
ctr[ch]++
mxocc = 0
maxch = 'a'
for(ch = a, b, c, d, e...)
if(ctr[ch] > maxocc) maxocc = ctr[ch] and maxch = ch
Output require info
hey you can figure out the problem ... atleast i can give to some extend same code , you can check it and try to solve your problem... This program finds the pattern in the string, now you can go through this program, and try to solve ur problem in your program by your own self.and try to do it by your own then only ur coding skills will get improved.and vote this answer if u fing it really helpful
#include<stdio.h>
#include<string.h>
int occur(char[],char[]);
int occur(char sent[],char pattern[])
{
int count=0;
for(int i=0,j=i;sent[i]!='\0';)
{
if(sent[i+j]==pattern[j]&&pattern[j]!='\0')
{
j++;
}
else if(j==strlen(pattern))
{
count++;
i=i+j;
j=0;
}
else
{
i++;
j=0;
}
}
return count;
}
int main()
{
char sent[] = "aabaabaaabbbabababddfggaabbbasab";
char pattern[] = "aba";
int result = occur(sent,pattern);
printf("\nNo of Occurrences --- > %d",result);
return 0;
}
You should simplify your code. For example there is not need to use those complex for-loops, you can use a for-each.
This code finds out the frequency of characters in a string and stores it in a Map.
import java.util.*;
public class CheckCharacterOccurence {
public static void main(String[] args) {
Map<Character, Integer> counting = new HashMap<Character, Integer>();
String testcase1 = "Helloooo";
for(char ch: testcase1.toCharArray()){
Integer freq = counting.get(ch);
counting.put(ch, (freq == null) ? 1 : freq + 1);
}
System.out.println(counting.size() + " distinct characters:");
System.out.println(counting);
}
}

Categories

Resources