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)

Find if a String is rotation of another String – Java Implementation

This is a simple yet popular Java interview question. Given two Strings how can you tell if they are rotations of each other? For example, the word “bottle” and “ottleb” or “ttlebo” are rotations of each other. Start thinking as writing this word in a tire uniformly and reading it from any character.

The solution is simple, if you know how to do it. If you take the first word and concatenate it with itself, any rotating string should be sub-string of such a concatenated word. And there you go !

The following is a java implementation of this simple algorithm. I have also provided a little advance solution by setting the case sensitivity flag to true or false.

package com.icodejava.blog.published;
/**
 * 
 * @author Kushal Paudyal
 * Created on: 1/9/2017
 * Last Modified on: 1/9/2017
 *
 */
public class StringRotationFinder {
	private static final boolean CASE_SENSITIVE = true;
	public static void main (String args []) {
		String firstString = "This is a beautiful house";
		String secondString ="a beautiful housethis is ";
		
		isRotated(firstString, secondString, CASE_SENSITIVE);
		isRotated(firstString, secondString, !CASE_SENSITIVE);
		
	}

	/**
	 * The rotated string is a subset of non-repeated String + non-repeated String
	 * 
	 * e.g. "abc abd" is original string and "c abda" which is a part of "abc abdabc abd"
	 * 
	 * This method uses a case sensitivity flag.
	 */
	private static void isRotated(String firstString, String secondString, boolean isCaseSensitive) {
		System.out.println("First String: " + firstString);
		System.out.println("Second String: " + secondString);
		boolean isRotated = false;
		if (firstString != null && secondString != null && firstString.length() == secondString.length()) {
			
			String concatenatedString = firstString + firstString;
			
			//Assuming the cases are not sensitive
			if(!isCaseSensitive) {
				concatenatedString = concatenatedString.toLowerCase();
				secondString = secondString.toLowerCase();
			}
			
			if (concatenatedString.contains(secondString)) {
				isRotated = true;
			}
		}
		
			
		System.out.println("First String and Second Strings are roated forms of is other (Case Sensitive: " +  isCaseSensitive +")? "  + isRotated );
		
	}

}

Here is the output of this program:

First String: This is a beautiful house
Second String: a beautiful housethis is 
First String and Second Strings are roated forms of is other (Case Sensitive: true)? false
First String: This is a beautiful house
Second String: a beautiful housethis is 
First String and Second Strings are roated forms of is other (Case Sensitive: false)? true

Cleaning Punctuation And White Spaces From A String

/**

* Created on Apr 12, 2007
* @author Kushal Paudyal
* www.sanjaal.com/java
*/

/**
* This utility class has method to remove punctuation 
* marks from a given string
*/

public class StringCleaner {
 private static String legalCharacterSet;	

/**
 * Default Constructor
 * Create a string that contains standard legal characters.
 * This string will be used to reference whether the 
*  characters in any 'to be cleaned'
 * string are to be kept or not.
 */

 public StringCleaner()
 {
 	legalCharacterSet ="ABCDEFGHIJKLMNOPQRSTUVWXYZ"+
			   "abcdefghijklmnopqrstuvwxyz"+
			   "1234567890-";
 }

/**
 * We may provide our own set of valid characters which 
 * are to be used on testing the validity.
 * This set is provided as a string containing 
 * valid characters.Order is not important.
 * @param validCharacterSet
 */

 public StringCleaner(String validCharacterSet )
 {
 	this.legalCharacterSet=validCharacterSet;
 }

/**
 * @param str The string to be cleaned 
 * (unnecessary characters and whitespaces removed)
 * @return Cleaned String
 */

 public String cleanString(String str)
 {
 	String cleanedString="";
 	for(int index=0;index
 	{

 		char currentCharacter=str.charAt(index);
 		if(legalCharacterSet.indexOf(currentCharacter)&gt;=0)
 		cleanedString+=currentCharacter;
 	}

 	return cleanedString;
 }
}