Find the first non-repeated character in an input String – Java Implementation

This class is a demonstration of how we can find the firs non-repeated character in a given string. The java code below is implemented with a flag for case sensitivity and shows you examples of how to use it.

For a sample text “This is that”, the first non-repeated character is “a” if your cases are not sensitive, however, if you cases are sensitive, the first non repeated character is “T”

package com.icodejava.blog.published;

import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @author Kushal Paudyal 
 * Created on: 01/05/2017 
 * Last Modified on: 01/05/2017
 *
 * This class demonstrates how we can find first non repeated character
 * in any given String. We will test for Case Sensitivity as well
 */

public class NonRepeatedCharacterFinder {

	final static boolean CASE_SENSITIVE = true;

	public static void main(String args[]) {
		String str = "Java Blog for junior Students";

		findFirstNonRepeatedCharacter(str, CASE_SENSITIVE);
		findFirstNonRepeatedCharacter(str, !CASE_SENSITIVE);

		str = "Apple is pretty yummy and healthy";

		findFirstNonRepeatedCharacter(str, CASE_SENSITIVE);
		findFirstNonRepeatedCharacter(str, !CASE_SENSITIVE);
		

		str = "ABba";
		findFirstNonRepeatedCharacter(str, CASE_SENSITIVE);
		findFirstNonRepeatedCharacter(str, !CASE_SENSITIVE);
	}

	private static void findFirstNonRepeatedCharacter(String originalString, boolean caseSensitive) {
		String str = originalString;

		if (str == null) {
			System.out.println("Not a valid string");
		}

		if (!caseSensitive) {
			str = str.toLowerCase();
		}

		Map<Character, Integer> countMap = new HashMap<Character, Integer>();

		// loop through the characters and find the character count
		for (int i = 0; i < str.length(); i++) {
			Character character = new Character(str.charAt(i));
			if (countMap.containsKey(character)) {
				Integer charCount = countMap.get(character);
				countMap.put(character, ++charCount);
			} else {
				countMap.put(character, 1);
			}
		}

		// Now find the first character that has a count of 1. Please note, we have iterated through the String characters. 
		// You can alternately iterate through the keys and find the corresponding values.
		boolean found = false;
		for (int i = 0; i < str.length(); i++) {
			char currentChar = str.charAt(i);
			if (countMap.get(currentChar) == 1) {
				System.out.println("FOUND. The first non repeated character in the String " + currentChar
						+ " (Case Sensitive: " + caseSensitive + ", String: " + originalString + ")");
				found = true;
				break;
			}

		}

		if (!found) {
			System.out.println("NOT FOUND: Non repeated character not found in the String." + " (Case Sensitive: "
					+ caseSensitive + ", String: " + originalString + ")");
		}

	}

}

OUTPUT

FOUND. The first non repeated character in the String J (Case Sensitive: true, String: Java Blog for junior Students)
FOUND. The first non repeated character in the String v (Case Sensitive: false, String: Java Blog for junior Students)
FOUND. The first non repeated character in the String A (Case Sensitive: true, String: Apple is pretty yummy and healthy)
FOUND. The first non repeated character in the String i (Case Sensitive: false, String: Apple is pretty yummy and healthy)
FOUND. The first non repeated character in the String A (Case Sensitive: true, String: ABba)
NOT FOUND: Non repeated character not found in the String. (Case Sensitive: false, String: ABba)

Finding if two Strings are Anagrams

Anagram is a word, a phrase or a sentence formed from another by rearranging it’s letters.

To find out whether given two entities are anagrams or not is an interesting piece for programmers. There are multiple ways to find anagrams. Here is the easy way I have done:

  1. I sorted both strings. 
  2. I wrote the sorting of the strings to ignore the case.
  3. Sorted words are trimmed to avoid any extra spacing. This is particularly important because sometimes, for example, a two word phrase can become three word phrase while re-arranging, thus have difference is number of spaces.
  4. Sorted strings are then compared to see if they are identical. If identical, then they form anagrams.

 

The Java code I wrote to find the anagrams is given below. I reused the String Sort code from my previous post.

package com.icodejava.blog.datastructure;

import java.util.Arrays;

/**
 * @author Kushal Paudyal
 * www.icodejava.com
 * Created On -  Feb 14, 2014
 * Last Modified On - Feb 14, 2014
 */
public class AnagramFinder {

	public static void main(String args[]) {
		String firstString = "Dormitory";
		String secondString = "Dirty Room";

		checkForAnagram(firstString, secondString);

		secondString = "Dirty Rooms";

		checkForAnagram(firstString, secondString);

	}

	private static boolean checkForAnagram(String firstString, String secondString) {

		System.out.println("Analyzing the following words for Anagrams: " + firstString + " , " + secondString);

		boolean result;

		if (firstString == null || secondString == null) {
			result = false;
		} else {
			String sortedFirstString = sortIgnoreCase(firstString).trim();
			String sortedSecondString = sortIgnoreCase(secondString).trim();

			System.out.println("Sorted First String: " + sortedFirstString);
			System.out.println("Sorted Second String: " + sortedSecondString);

			result = sortedFirstString.equalsIgnoreCase(sortedSecondString);
		}

		System.out.println("ANAGRAM RESULT - " + result + "\n\n");

		return result;

	}

	/**
	 * @param string
	 *            - String to be sorted
	 * @return sorted string
	 */
	private static String sortIgnoreCase(String string) {
		if (string == null) {
			return null;
		}

		char[] characters = string.toUpperCase().toCharArray();
		Arrays.sort(characters);
		return new String(characters);

	}

}

The output of this program is:

Analyzing the following words for Anagrams: Dormitory , Dirty Room
Sorted First String: DIMOORRTY
Sorted Second String: DIMOORRTY
ANAGRAM RESULT - true


Analyzing the following words for Anagrams: Dormitory , Dirty Rooms
Sorted First String: DIMOORRTY
Sorted Second String: DIMOORRSTY
ANAGRAM RESULT - false