Count Duplicate letters - java

I want to get a string count any letter in the string how many time it's appeared in the string,and print the letter and the number So that what i did:
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
String str;
Scanner in = new Scanner(System.in);
System.out.println("enter name");
str = in.nextLine();
char[] c1 = str.toCharArray();
int[] f = new int[str.length()];
for(int i=0;i<str.length();i++) {
for(int j=0;j<str.length();j++) {
if(c1[i]==c1[j]) {
f[i]++;
}
}
}
for(int k=0;k<c1.length;k++) {
for(int l=0;l<c1.length;l++) {
if(c1[k]==c1[l]) {
if(l!=k) {c1[k]=0;f[k]=0;}
}
}
System.out.println(c1[k]+"="+f[k]);
}
}
}
There are two problems:
1. when i print it's printing the duplicated letter twice(or thrice or more depends how many times the letter is in the string).
so i added the another 2 loops(k and l) that deletes the duplicated letters,but now instead of the duplicated letter it's print me: an square and a zero,how i can just get delete the letter and the number from the char and int array's?(for example when i insters the name "elichai" i get:
e=1
l=1
(an square)=0
c=1
h=1
a=1
i=2
2.The letter it deletes is the second letter not the first
(in "elichai" example it's deleted the first 'i' instead of the second 'i')
Thanks!

Different approach to solve your problem, but this is how I would probably do it:
String input = "Whatever";
Map<Character, Integer> charCounter = new LinkedHashMap<>(); // respects insertion order
for (char c : input.replaceAll("\\s+", "").toCharArray()) { // ignore spaces
Integer count = charCounter.get(c);
count = count == null ? 0 : count;
charCounter.put(c, count + 1);
}
System.out.println(charCounter);

class Twice_Occuring
{
void main(String s)
{
int count=0;
for(int i=0;i<s.length();i++)
{
char c=s.charAt(i);
int ind1=s.indexOf(c,i);
int ind2=s.indexOf(c,i+1);
if(ind2-ind1==1)
{System.out.print(c+" ");count++;}
}
System.out.println("\n Number of counts = "+count);
}
}

Related

Find the occurrence of each character in a given string

"I want to find and print the occurrence of each character of given string and i have build my own logic but there is some problem.for example if i gave input as 'JAVA'.
the output that my program produce will be
J 1
A 2
V 1
A 1
Expected output :
J 1
A 2
V 1
i doesn't want to print A again. I hope you all get it what is the problem in my code."
import java.util.Scanner;
public class FindOccuranceOfCharacter {
public static void main(String[] args) {
// TODO Auto-generated method stub
String x;
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
x = input.nextLine();
x = x.toUpperCase();
int size = x.length();
for(int i =0;i<size;i++) {
int count=1;
char find = x.charAt(i);
for(int j=i+1;j<size;j++) {
if(find == x.charAt(j)) {
count++;
}
}
System.out.printf("%c\t%d",x.charAt(i),count);
System.out.println();
}
}
}
The reason your code prints the way it does is that your loop prints each character (and subsequent matches) for a given index. You really need to store the character and counts in a data structure with one loop, and then display the counts with a second. A LinkedHashMap<Character, Integer> is perfect for your use case (because it preserves key insertion order, no additional logic is needed to restore input order). Additional changes I would make include using String.toCharArray() and a for-each loop. Like,
Map<Character, Integer> map = new LinkedHashMap<>();
for (char ch : x.toUpperCase().toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
for (char ch : map.keySet()) {
System.out.printf("%c\t%d%n", ch, map.get(ch));
}
Which I tested with x equal to JAVA and got (as requested)
J 1
A 2
V 1
Using hashMap it's easy to accumulate the number of occurrences and you can easily print iterating the HashMap.
This is the code:
public class FindOccuranceOfCharacter {
public static void main(String[] args) {
String x;
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
x = input.nextLine();
HashMap<Character,Integer> occurance = new HashMap<Character,Integer>();
x = x.toUpperCase();
int size = x.length();
for(int i =0;i<size;i++) {
int count=1;
char find = x.charAt(i);
occurance.put(find, occurance.getOrDefault(find, 0) + 1);
}
for (Character key : occurance.keySet()) {
Integer value = occurance.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
}
This is not an optimal solution, but I have tried to change your code as little as possible:
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
// use a StringBuilder to delete chars later on
StringBuilder x = new StringBuilder(input.nextLine().toUpperCase());
for(int i=0;i<x.length();i++) {
int count=1;
char find = x.charAt(i);
// go through the rest of the string from the end so we do not mess up with the index
for(int j=x.length()-1;j>i;j--) {
if(find == x.charAt(j)) {
count++;
// delete counted occurences of the same char
x.deleteCharAt(j);
}
}
System.out.printf("%c\t%d",x.charAt(i),count);
System.out.println();
}
}
My more preferred Java stream would look like this:
input.nextLine().toUpperCase().chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.forEach((k, v) -> System.out.println(k + "\t" + v));

Determining the highest word alphabetically without arrays in java

I have been trying to write a program that does 2 things, finds the longest word in a user generated string and finding the highest word in alphabetical order. I have the longest word working fine, but I cant figure out the alphabetical problem to save my life. the problem I'm running into is how it is comparing the words running in the for loops. Any help would be appreciated!
/*
CSC 190
Hw7
Ryan Burchfield
10/19/17
Purpose: Take a string and return both the Longest and largest words in the String.
*/
package hw7;
import java.util.Scanner;
class MyString{
String s;
MyString( String s1 ){
s=s1;
}
void setString(String s1){
s=s1;
}
String getLongest(String s1){
s1 = s1 +" ";
int length = s1.length();
String temp="", longestw="";
char ltr;
int templ, longest=0;
for(int i=0; i<length;i++){
ltr = s1.charAt(i);
if(ltr!=' ' && ltr!=',' && ltr!='.'){
temp=temp+ltr;
}
else{
templ=temp.length();
if(templ>longest){
longest=templ;
longestw=temp;
}
temp="";
}
}
return longestw;
}
String getLargest(String s1){
s1= s1 + " ";
String temp="", curWord="",largestW="";
char ltr;
for(int i=0; i<s1.length(); i++){
ltr = s1.charAt(i);
if(ltr!=' ' && ltr!=',' && ltr!='.'){
temp= temp + ltr;
}else{
char ltr1;
for(int j=0; j<s1.length(); j++){
ltr1 = s1.charAt(j);
if(ltr1!=' ' && ltr1!=',' && ltr1!='.'){
curWord= curWord + ltr1;
}
else{
int largest = temp.compareToIgnoreCase(curWord);
System.out.println(temp+","+curWord+","+temp.compareToIgnoreCase(curWord));
System.out.println(largest);
if(largest > 0){
largestW=curWord;
}else{
largestW=temp;
}
curWord="";
temp="";
}
}
}
}
return largestW;
}
}
public class Hw7 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a series of words: ");
String s = in.nextLine();
MyString s1 = new MyString(s);
System.out.println("The longest word is: " + s1.getLongest(s));
System.out.println("The largest word is: " + s1.getLargest(s));
}
}
if(largest > 0){
largestW=curWord;
}else{
largestW=temp;
}
This is where the program goes wrong. You did not compare currWord / temp with largestW
A better way to write getLargest() is to use the same way as getLongest(), i.e. using one loop, and compare largestW with temp every time (if largestW is empty then just set largestW = temp)
I would solve this with a single method that takes a Comparator<String> and the input String; construct a Scanner using the Scanner(String) constructor and modify the delimiter using Scanner#useDelimiter(String) to consume white space, commas, and literal '.'. Then use the supplied Comparator to compare the tokens available through the Scanner. Like,
static String findWord(Comparator<String> comp, String s1) {
Scanner sc = new Scanner(s1);
sc.useDelimiter("[\\s,\\.]+");
String max = null;
while (sc.hasNext()) {
String token = sc.next();
if (max == null || comp.compare(max, token) < 0) {
max = token;
}
}
return max;
}
Then, assuming you're using Java 8+, main can be written using Comparators already available like -
Comparator<String> stringLengthComparator = Comparator.comparingInt(
String::length);
Comparator<String> stringAlphaComparator = Comparator.naturalOrder();
Scanner in = new Scanner(System.in);
System.out.println("Please enter a series of words: ");
String sentence = in.nextLine();
System.out.printf("Longest: %s%n", findWord(stringLengthComparator, sentence));
System.out.printf("Lexically: %s%n", findWord(stringAlphaComparator, sentence));
But, if you're using an earlier version - or you want to better understand what it does, the exact same code will work if you replace the two Comparators with equivalent code - like
Comparator<String> stringLengthComparator = new Comparator<String>() {
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
};
Comparator<String> stringAlphaComparator = new Comparator<String>() {
public int compare(String a, String b) {
return a.compareTo(b);
}
};
There's a lot of code there, nearly all of which is unnecessary.
Try this:
String longest = Arrays.stream(s.split(" +")).sort(comparing(String::length).reversed()).findFirst().get();
String highest = Arrays.stream(s.split(" +")).sort().reduce((a,b) -> b).get();
Note: Read and understand the code well before you submit your assignment.
Disclaimer: Code may not compile or even work as it was thumbed in on my phone (but there's a reasonable chance it will work)
As your post you can get the longest word. I will show you how to get the highest letter in alphabetical order of the longest word.
There is a method call toCharArray() you can use this method to make letter array of given word.
Than you can use casting to get integer value of the given char value
Then you can compare that integer value to get the highest integer value
Once you have the highest integer value cast that int value to char to take the letter
Following links to more information
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray()
http://javaseeeedu.blogspot.com/2015/12/casting-part-1.html
I have change your code try it
import java.util.Scanner;
class MyString{
String s;
MyString( String s1 ){
s=s1;
}
void setString(String s1){
s=s1;
}
String getLongest(String s1){
s1 = s1 +" ";
int length = s1.length();
String temp="", longestw="";
char ltr;
int templ, longest=0;
for(int i=0; i<length;i++){
ltr = s1.charAt(i);
if(ltr!=' ' && ltr!=',' && ltr!='.'){
temp=temp+ltr;
}
else{
templ=temp.length();
if(templ>longest){
longest=templ;
longestw=temp;
}
temp="";
}
}
return longestw;
}
char getLargest(String s1){
int max = 0;
char []arr = s1.toCharArray();
int temp[] = new int[arr.length];
for(int i=0;i<arr.length;i++){
temp[i] = (int)arr[i];
if(i!=0){
if(temp[i-1] < temp[i]){
max = temp[i];
}else{
max = temp[i-1];
}
}
}
return (char)max;
}
}
class Demo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a series of words: ");
String s = in.nextLine();
MyString s1 = new MyString(s);
System.out.println("The longest word is: " + s1.getLongest(s));
System.out.println("The largest letter is: " + s1.getLargest(s1.getLongest(s)));
}
}

How to adjust the given string such that the first letter after the space becomes Upper case in java?

So I was solving problem from one competitive websites.And I have completed 75% of the constraint.But the condition where the first word in the given sentence after space must be uppercase.I tried but it does not give correct answer.
For example if the sentence is "This is" is the sentence it must be changed to "ThIs Is".So help me.
And my code is as follows
import java.util.Scanner;
public class DancingSentence {
public String makeDancing(String sentence)
{
//sentence=sentence.replace("\\s+","");
//String sen = null;
char[] sen = sentence.toCharArray();
int i = 0;
System.out.println(sen.length);
if(i==0)
{
sen[i]=sen[i];
}
for(i=1;i<sen.length;i++)
{
// if()
if (i%2==0)
{
sen[i] = (char)(sen[i]-32);
}
//if((int)sen[i]==32)
if(Character.isWhitespace(sen[i]))
{
//System.out.print(" ");
sen[i+1]=Character.toUpperCase(sen[i+1]);
//i+=1;
}
}
sentence = sen.toString().copyValueOf(sen);
//sentence = sentence.replace("", "\\s+");
//System.out.println(sentence);
return sentence;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String sentence = sc.nextLine();
//sentence=sentence.replaceAll("\\s+","");
DancingSentence ds = new DancingSentence();
String result=ds.makeDancing(sentence);
System.out.println(result);
}
}
Your logic is almost right. If the index is even (i % 2 == 0), you convert the character to uppercase. If you encounter a whitespace, you just skip it and don't increase your variable that you use for determining even positions.
public String makeDancing(String sentence) {
char[] sen = sentence.toCharArray();
int mod = 0; //counts just letters
for(int i=0; i < sen.length; i++) {
if(Character.isWhitespace(sen[i])) { //if character is a whitespace, skip it
continue;
}
if (mod % 2 == 0) { //if it is an even position, make it uppercase
sen[i] = Character.toUpperCase(sen[i]);
}
mod++;
}
sentence = new String(sen);
return sentence;
}

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");
}
}
}

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