Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Count Num of Letters In Common

  1. #1
    Member
    Join Date
    Aug 2020
    Posts
    42
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Question Count Num of Letters In Common

    Hello, I am working on an exercise that's giving me a bit of a problem. The goal is to output the number of letters two Strings have in common. I've thought of a method where I take the Strings, throw them into a method that sorts them, then have another method to the removing of any extra letters. Example: (aabccde) -> (abcde).
    For the most part, what I have thus far does work for "most" scenarios, but not all. The String, "aaabcdd" works fine within the method and is returned as "abcd" yet, "aabc" isn't returned as "abc". I've tried changined the length within the loops, the number of times it itterates, avoiding going out of bounds. I'm not sure what needs to be changed. Also, there is more than likely a more efficient way of doing what I'm trying to do, perhaps using what's called "Java regex" but I'm not at the level of having learned that yet. Here's what I have thus far below:

    Note: Ignore the comments, they're more for me so that I don't forget what does what or what I'm trying to accomplish.

    //	Currently working on writing code that will output the number of letters, two Strings share in common
     
    import java.util.Arrays;
     
    public class TestingCode {
     
    	public static void main(String[] args) {
     
    		String str1 = "aabc";
    		String str2 = "aaabcdd";
     
    		System.out.println(lettersCommon(str1, str2));
     
    	}//end main
     
    	public static int lettersCommon(String str1, String str2) {
     
    		int count = 0;
     
    		//	We first sort the given Strings using another method called 'sortString'
    		str1 = sortString(str1);
    		str2 = sortString(str2);
     
    		//	We then remove the repeats within the sorted string using a method called 'removeRepeatLetters'
    		str1 = removeRepeatLetters(str1);
    		str2 = removeRepeatLetters(str2);
     
    		//	For simplicity, we store the lengths of both Strings here
    		int len1 = str1.length();
    		int len2 = str2.length();
     
    		//	We count the number of letters in common between both Strings below and return the number of letters in common
    		if(len1 >= len2) {
    			for(int i = 0; i < len2; i++) {
    				for(int j = 0; j < len1; j++) {
    					if(str2.charAt(i) == str1.charAt(j))
    						count++;
    				}
    			}
    		}else {
    			for(int i = 0; i < len1; i++) {
    				for(int j = 0; j < len2; j++) {
    					if(str1.charAt(i) == str2.charAt(j))
    						count++;
    				}
    			}
    		}
     
    		return count;
    	}
     
    	//	Removes repeated letters in String (needs fixing)
    	public static String removeRepeatLetters(String str) {
     
    		//	'result' is used to store the String w/o repeated letters
    		String strNoRepeat = "";
     
    		//	Length of String given to method
    		int len = str.length();
     
    		//	Removing repeated letters from str1
    		for(int i=0; i < len-1; i++) {
    			if(!(str.charAt(i) == str.charAt(i+1))) {
    				strNoRepeat += str.substring(i,i+2);
    				i++;
    			}
    		}
     
    		System.out.println(strNoRepeat);
     
    		return strNoRepeat;
    	}
     
    	//	Sorts Strings (works)
    	public static String sortString(String inputString) {
     
    		char tempArray[] = inputString.toCharArray();
     
    		Arrays.sort(tempArray);
     
    		return String.valueOf(tempArray);
    	}
     
    }//end class

    Fixed Version:
    //	Currently working on writing code that will output the number of letters, two Strings share in common
     
    import java.util.Arrays;
     
    public class TestingCode {
     
    	public static void main(String[] args) {
     
    		String str1 = "ababc";
    		String str2 = "aababcdde";
     
    		System.out.println(lettersCommon(str1, str2));
     
    	}//end main
     
    	public static int lettersCommon(String str1, String str2) {
     
    		int count = 0;
     
    		//	We first sort the given Strings using another method called 'sortString'
    		str1 = sortString(str1);
    		str2 = sortString(str2);
     
    		//	We then remove the repeats within the sorted string using a method called 'removeRepeatLetters'
    		str1 = removeRepeatLetters(str1);
    		str2 = removeRepeatLetters(str2);
     
    		//	For simplicity, we store the lengths of both Strings here
    		int len1 = str1.length();
    		int len2 = str2.length();
     
    		//	We count the number of letters in common between both Strings below and return the number of letters in common
    		if(len1 >= len2) {
    			for(int i = 0; i < len2; i++) {
    				for(int j = 0; j < len1; j++) {
    					if(str2.charAt(i) == str1.charAt(j))
    						count++;
    				}
    			}
    		}else {
    			for(int i = 0; i < len1; i++) {
    				for(int j = 0; j < len2; j++) {
    					if(str1.charAt(i) == str2.charAt(j))
    						count++;
    				}
    			}
    		}
     
    		return count;
    	}
     
    	//	Removes repeated letters in String (needs fixing)
    	public static String removeRepeatLetters(String str) {
     
    		//	'result' is used to store the String w/o repeated letters
    		String strNoRepeat = "";
     
    		//	Length of String given to method
    		int len = str.length();
     
    		//	Removing repeated letters from str1
    		for(int i=0; i < len-1; i++) {
    			if(!(str.charAt(i) == str.charAt(i+1))) {
    				strNoRepeat += str.charAt(i);
    			if(i==len-2 && (!(str.charAt(len-2) == str.charAt(len-1))))
    				strNoRepeat += str.substring(len-1);
    			}
    		}
     
    		System.out.println(strNoRepeat);
     
    		return strNoRepeat;
    	}
     
    	//	Sorts Strings
    	public static String sortString(String inputString) {
     
    		char tempArray[] = inputString.toCharArray();
     
    		Arrays.sort(tempArray);
     
    		return String.valueOf(tempArray);
    	}
     
    }//end class
    Last edited by HyperRei; August 21st, 2021 at 10:02 PM.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Count Num of Letters In Common

    Can you describe the logic for solving the problem in English?
    List the steps the program needs to take.

    What data structures or java classes can be used to solve the problem?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Aug 2020
    Posts
    42
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Count Num of Letters In Common

    I'll try to describe the logic the best I can. I'll do it in the steps below:

    Step 1: We pass in our Strings into the method, where the first thing done by the method is to create an int variable 'count' to track the number of letters in common between both Strings.
    Step 2: We pass in each String individually, into a method called 'sortString' then store the returned value
    Note: within 'sortString' store each letter within the String into a char array, where we then use 'Arrays.sort()' on the char array, to sort the String which is then returned (sorted so that repeated letters are next to each other)
    Step 3: We pass the now sorted String into a method called 'removeRepeatLetters' in an effort to remove repeated letters.
    Note: within 'removeRepeatedLetters' a String variable is created called 'strNoRepeat' to hold the resulted String after having repeats removed. The process to remove repeats is to check to chars at a time and see if they're different, and if so, we add them to the String we created to hold them, then I added an extra 'i++' so that
    when it comes around to the loop, we get that 2nd 'i++' and we skip over the 2 letters we just added that we confirmed to not be the same. Any letters that are the same are ignored and we continue moving forward through the String.
    Step 4: After removing the repeated letters, we store the returned String from the 'removeRepeatLetters' method and store the lengths of both Strings into int variables len1 and len2 (we use len1 and len2 to check which of the Two Strings, is shorter than the other)
    Step 5: Finally, we check if the letter at the first index within the String matches with any letter within the 2nd by using a nested loop. If we have a match, we do count++ and finally return the resulted count.

    As for Data structures, not sure if it counts since it's imported but I only use the java.util.Arrays just for the sorting method. Every other bit of code doesn't use a data structure/class to my knowledge. I'm still in the process of learning CS/Java terms so I apologize if I misunderstood what was asked/gave a different answer.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Count Num of Letters In Common

    Ok, start with the methods one at a time. Test it and fix the problems before going to the next method.
    Don't do it all in one test. Work on them one at a time.
    Are these what the methods do?
    1) sort char in each String
    2) remove duplicates
    3) count matches
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Aug 2020
    Posts
    42
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Count Num of Letters In Common

    Yes, that's exactly what each method does. Also, I know the problem is within the method that removes duplicates. I believe it to be a logic error as it doesn't seem to take into account the last two letters or the last letter. I'm not sure how to go about this, logical I think you could say, to make it work. Perhaps there are some built-in functions/imports I could use for this part, but I'm unsure what to look up, and anything I've searched has led to a dead end thus far.

    --- Update ---

    Found a way to make it work, just needed one more if-statement. Just wanted to update, but thanks for the help.

Similar Threads

  1. Replies: 1
    Last Post: April 11th, 2018, 01:50 PM
  2. Replies: 10
    Last Post: July 1st, 2014, 02:41 PM
  3. Column count doesn't match value count at row 1
    By Tyluur in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 30th, 2012, 01:31 AM
  4. [SOLVED] Words with and without capital letters.
    By Purple01 in forum Java Theory & Questions
    Replies: 3
    Last Post: September 19th, 2012, 01:03 PM
  5. How to remove letters
    By noobish in forum Java Theory & Questions
    Replies: 13
    Last Post: October 3rd, 2009, 10:36 PM

Tags for this Thread