0% found this document useful (0 votes)
29 views

Strings Programs Expl

The document discusses 4 approaches to find the first non-repeated character in a string. It also discusses using maps and streams to count character frequencies. It provides code examples of counting duplicate characters in a string using maps and streams. It also discusses handling Unicode characters and surrogate pairs.

Uploaded by

SAITEJA GUNDAPU
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Strings Programs Expl

The document discusses 4 approaches to find the first non-repeated character in a string. It also discusses using maps and streams to count character frequencies. It provides code examples of counting duplicate characters in a string using maps and streams. It also discusses handling Unicode characters and surrogate pairs.

Uploaded by

SAITEJA GUNDAPU
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

First Non Repeated Character :

S,a,s,l,p,a,p,i

Approach 1 :

First one for loop for getting the character and check the remaining chars any char is found in the other
loop and if it fetches then count increament and I !=j and break and check for the count==0 that is the
one which is not at all increamented
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
int count = 0;
for (int j = 0; j < str.length(); j++) {
if (ch == str.charAt(j) && i != j) {
count++;
break;
}
}
if (count == 0) {
return ch;
}
}

Approach 2:

HashMap will be populating the charcter and the occurences of each


character,Then again a for loop for checking the charcter
getValue()==1 condition

 Imporatant Point here is compute function of Map (which we already noted


earlier how the if the mapping for the key,value is not found)

Map<Character, Integer> chars = new LinkedHashMap<>();


// or use for(char ch: str.toCharArray()) { ... }
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
chars.compute(ch, (k, v) -> (v == null) ? 1 : ++v);
}
for (Map.Entry<Character, Integer> entry : chars.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}

Approach 3 :
=====
// here we have the string chnars and then map to Obj we can directly have the
intstream no chaning here and then collecting the map using the grouping by and as
the intvalue so we have the int and collectors.counting will give the long value
//from the Stream we will go thourgh it and then filter out the values which has 1 L
and then use the findFirstand then use the getKey for the Map.Entry::getKey
Map<Integer, Long> chs = str.chars()
.mapToObj(cp -> cp)
.collect(Collectors.groupingBy(Function.identity(),
LinkedHashMap::new, Collectors.counting()));
return (char) (int) chs.entrySet().stream()
.filter(e -> e.getValue() == 1L)
.findFirst()
.map(Map.Entry::getKey)
.orElse(Integer.valueOf(Character.MIN_VALUE));

Approach 4 : Other way we can use the code points as well

Map<Integer, Long> chs = str.codePoints()


.mapToObj(cp -> cp)
.collect(Collectors.groupingBy(Function.identity(),
LinkedHashMap::new, Collectors.counting()));

int cp = chs.entrySet().stream()
.filter(e -> e.getValue() == 1L)
.findFirst()
.map(Map.Entry::getKey)
.orElse(Integer.valueOf(Character.MIN_VALUE));

Integer and Character are final classes and cannot be


extended and the values for the Integer max and
Integer Min we need to check
public final class Integer extends Number implements Comparable<Integer> {
/**
* A constant holding the minimum value an {@code int} can
* have, -2<sup>31</sup>.
*/
@Native public static final int MIN_VALUE = 0x80000000;

/**
* A constant holding the maximum value an {@code int} can
* have, 2<sup>31</sup>-1.
*/
@Native public static final int MAX_VALUE = 0x7fffffff;

public final
class Character implements java.io.Serializable, Comparable<Character> {
/**
* The minimum radix available for conversion to and from strings.
* The constant value of this field is the smallest value permitted
* for the radix argument in radix-conversion methods such as the
* {@code digit} method, the {@code forDigit} method, and the
* {@code toString} method of class {@code Integer}.
*
* @see Character#digit(char, int)
* @see Character#forDigit(int, int)
* @see Integer#toString(int, int)
* @see Integer#valueOf(String)
*/
public static final int MIN_RADIX = 2;

/**
* The maximum radix available for conversion to and from strings.
* The constant value of this field is the largest value permitted
* for the radix argument in radix-conversion methods such as the
* {@code digit} method, the {@code forDigit} method, and the
* {@code toString} method of class {@code Integer}.
*
* @see Character#digit(char, int)
* @see Character#forDigit(int, int)
* @see Integer#toString(int, int)
* @see Integer#valueOf(String)
*/
public static final int MAX_RADIX = 36;

/**
* The constant value of this field is the smallest value of type
* {@code char}, {@code '\u005Cu0000'}.
*
* @since 1.0.2
*/
public static final char MIN_VALUE = '\u0000';

/**
* The constant value of this field is the largest value of type
* {@code char}, {@code '\u005CuFFFF'}.
*
* @since 1.0.2
*/
public static final char MAX_VALUE = '\uFFFF';
Found character: ’

My Approach is similar but instead of Integer we can use the charcter in mapToObj
which results in the Map<Character,Long>

Map<Character, Long> chs = str.chars()


.mapToObj(cp -> (char)cp)
.collect(Collectors.groupingBy(Function.identity(),
LinkedHashMap::new, Collectors.counting()));

System.out.println((char) (int) chs.entrySet().stream()


.filter(e -> e.getValue() == 1L)
.findFirst()
.map(Map.Entry::getKey)
.orElse(Character.MIN_VALUE)
);

return (char) (int) chs.entrySet().stream()


.filter(e -> e.getValue() == 1L)
.findFirst()
.map(Map.Entry::getKey)
.orElse(Character.MIN_VALUE);

Some Programs in Main :

package modern.challenge;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.sun.xml.internal.fastinfoset.stax.events.CharactersEvent;

public class Main {

private static final String TEXT = "Be strong, be fearless, be beautiful. "
+ "And believe that anything is possible when you have the right "
+ "people there to support you. ";
// Ӝ -> Unicode: \u04DC, Code Point: 1244
// 💕 -> Unicode: \uD83D\uDC95, Code Point: 128149
// 🎼 -> \uD83C\uDFBC, Code Point: 127932
// � ->\uD83D\uDE0D, Code Point: 128525
private static final String TEXT_CP = TEXT + "� I love 💕 you Ӝ so much
💕 � 🎼🎼🎼!";

public static void main(String[] args) {

System.out.println("Input text: \n" + TEXT + "\n");

System.out.println("\n\nASCII or 16 bits Unicode characters (less than 65,535


(0xFFFF)) examples:\n");

System.out.println("HashMap based solution:");

programToReverseString();

checkPalindrome();

countAllCharacterCountString();

countACharcterFrequencyInSentence();

//permutations and combinations of string (Dont repeat instead use a set to


remove duplicates)

long startTimeV1 = System.nanoTime();

Map<Character, Integer> duplicatesV1 =


Strings.countDuplicateCharactersV1(TEXT);

displayExecutionTime(System.nanoTime()-startTimeV1);
System.out.println(Arrays.toString(duplicatesV1.entrySet().toArray()));
// or: duplicatesV1.forEach( (k, v) -> System.out.print(k + "="+ v + ", "));

System.out.println();
System.out.println("Java 8, functional-style solution:");
long startTimeV2 = System.nanoTime();

Map<Character, Long> duplicatesV2 = Strings.countDuplicateCharactersV2(TEXT);


displayExecutionTime(System.nanoTime()-startTimeV2);
System.out.println(Arrays.toString(duplicatesV2.entrySet().toArray()));
// or: duplicatesV2.forEach( (k, v) -> System.out.print(k + "="+ v + ", "));

System.out.println("\n--------------------------------------\n");
System.out.println("Input text: \n" + TEXT_CP + "\n");
System.out.println("\n\nIncluding Unicode surrogate pairs examples:\n");
System.out.println("HashMap based solution:");
long startTimeV3 = System.nanoTime();

Map<String, Integer> duplicatesV3 =


Strings.countDuplicateCharactersVCP1(TEXT_CP);

displayExecutionTime(System.nanoTime()-startTimeV3);
System.out.println(Arrays.toString(duplicatesV3.entrySet().toArray()));
// or: duplicatesV3.forEach( (k, v) -> System.out.print(k + "="+ v + ", "));

System.out.println();
System.out.println("Java 8, functional-style solution:");
long startTimeV4 = System.nanoTime();

Map<String, Long> duplicatesV4 =


Strings.countDuplicateCharactersVCP2(TEXT_CP);

displayExecutionTime(System.nanoTime()-startTimeV4);
System.out.println(Arrays.toString(duplicatesV4.entrySet().toArray()));
// or: duplicatesV4.forEach( (k, v) -> System.out.print(k + "="+ v + ", "));
}

private static void countACharcterFrequencyInSentence() {


// Count a Specific Character In the String
// 1st Way : Replace with "" of that particular character and count the
// difference between actual input and the replaced string

int countOfChar = TEXT.length() - TEXT.replace("e", "").length();


System.out.println("The No Of Characters of 'e' in :" + TEXT + " is :" +
countOfChar);

// Second way : Using Java 8 Filter and Count function


// Conversion of int to long is easy Just a type Casting
int countOfCharcterInString = (int) TEXT.chars().mapToObj(ch -> (char)
ch).filter(ch -> ch == 'e').count();
// Conversion of int to Long we need to use the 'intValue()' method to
// do that
int countOfCharcterInString2 = TEXT.chars().mapToObj(ch -> (char)
ch).filter(ch -> ch == 'e')
.collect(Collectors.counting()).intValue();
// Other way is to use reducing at the end if needed in the integer
int countOfCharcterInString3 = TEXT.chars().mapToObj(ch -> (char)
ch).filter(ch -> ch == 'e')
.collect(Collectors.reducing(0, e -> 1, Integer::sum));

// Other way is to use reducing at the end if needed in the Long format
int countOfCharcterInString4 = TEXT.chars().mapToObj(ch -> (char)
ch).filter(ch -> ch == 'e')
.collect(Collectors.reducing(0L, e -> 1L,
Long::sum)).intValue();

// Other way is to use reducing at the end if needed in the int format
int countOfCharcterInString5 = TEXT.chars().mapToObj(ch -> (char)
ch).filter(ch -> ch == 'e')
.collect(Collectors.reducing(0, e -> 1, Integer::sum));

System.out.println("The No Of Characters of 'e' in :" + TEXT + " is :" +


countOfCharcterInString);
System.out.println("The No Of Characters of 'e' in :" + TEXT + " is :" +
countOfCharcterInString2);
System.out.println("The No Of Characters of 'e' in :" + TEXT + " is :" +
countOfCharcterInString3);
System.out.println("The No Of Characters of 'e' in :" + TEXT + " is :" +
countOfCharcterInString4);
System.out.println("The No Of Characters of 'e' in :" + TEXT + " is :" +
countOfCharcterInString5);

// Traditional method 1: take count variable and using the if condition


// to increament the variable when an instance is found
String[] charcterArray = TEXT.split("");
int countOfCharacterInASentence = 0;
for (String charact : charcterArray) {
if (charact.equals("e")) {
countOfCharacterInASentence++;
}
}
System.out.println("The No Of Characters of 'e' in :" + TEXT + " is :" +
countOfCharacterInASentence);
// Traditional method 2: take count variable and using the if condition
// to increament the variable when an instance is found

int countOfCharacterInASent = 0;
for (int i = 0; i < TEXT.length(); i++) {
if (TEXT.charAt(i) == 'e') {
countOfCharacterInASent++;
}
}
System.out.println("The No Of Characters of 'e' in :" + TEXT + " is :" +
countOfCharacterInASent);
}

private static void countAllCharacterCountString() {


//count each character occurences in a string

//Traditional way get chars array and include that in the key if not
available and put value =1 and from then increament the value

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


for(int i=0;i<TEXT.length();i++){
if(!countNoOfOccurencesEachChar.containsKey(TEXT.charAt(i))){
countNoOfOccurencesEachChar.put(TEXT.charAt(i), 1);
}else{
countNoOfOccurencesEachChar.put(TEXT.charAt(i),
(countNoOfOccurencesEachChar.get(TEXT.charAt(i))+1));
}
}
System.out.println(countNoOfOccurencesEachChar);
//Get the map using the collectors group by Java 8
Map<Character,Long>charCountMap=TEXT.chars().mapToObj(ch-
>(char)ch).collect(Collectors.groupingBy(Character::new,Collectors.counting()));
System.out.println(charCountMap);

// using merge
Map<Character,Integer> freqMapSecond= new HashMap<>();
for (Character c : TEXT.toCharArray()) {
freqMapSecond.merge(c, 1, Integer::sum);
}

String s = "abcaba";
Map<Character, Integer> frequencies = s.chars().boxed()
.collect(Collectors.toMap(
// key = char
k -> Character.valueOf((char) k.intValue()),
v -> 1, // 1 occurence
Integer::sum));

// Map<Character, Long> frequency =


// TEXT.chars()
// .mapToObj(c -> (char)c)
// .collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));

String string = "aasjjikkk";

Map<Character, Long> characterFrequency = string.chars() // creates an


IntStream
.mapToObj(c -> (char) c) // converts the IntStream to Stream<Character>
.collect(Collectors.groupingBy(c -> c, Collectors.counting())); //
creates a

//============
// Map<Character, Integer> frequency =
// str.chars()
// .mapToObj(c -> (char)c)
// .collect(Collectors.groupingBy(Function.identity(),
Collectors.summingInt(c -> 1)));
//Other ways using map.

private static void checkPalindrome() {


// Program to check the string is palindrome
//so I have to write the code in traditional way
//madam --> odd ->n/2 check andf compare Left Right digits until the middle
so intialize with o and max legth
//abccba --> even

String oddPalindrome="MADAM";
int left=0,right=oddPalindrome.length()-1;
boolean flag=true;
for (int i=0;i<oddPalindrome.length()/2;i++){
while(left<right){
if(!(oddPalindrome.charAt(left)==oddPalindrome.charAt(right))){
flag= false;
break;
}
left++;
right--;
}
}
if(flag){
System.out.println("The given String :"+oddPalindrome+"is palindrome");
}

//Using Other Approach with out declaration or initialization of variables


i.e just use the values over there
//try using the strinhg methods split and reverse and then join

String palindrome="MADdAM";
String[] palindromeChars=palindrome.split("");
StringBuilder sbpalindrome= new StringBuilder();
for(int i=palindromeChars.length-1;i>=0;i--){
sbpalindrome.append(palindromeChars[i]);
}
System.out.println(sbpalindrome);
if(palindrome.equals(sbpalindrome)){
System.out.println("Palindrome");
}

// Easy way i.e String Builder approach


String evenPalindrome="abccba";
String reverseString= new StringBuilder(evenPalindrome).reverse().toString();
if(evenPalindrome.equals(reverseString)){
System.out.println("Given String is palindrome");
}

}
private static void programToReverseString() {
//Program to reverse the string
//1st way going end to end by taking the string builder
StringBuilder reverseString = new StringBuilder();
for(int i=TEXT.length()-1;i>=0;i--){
reverseString.append(TEXT.charAt(i));
}
System.out.println(reverseString.toString());
//Java 8 way to map the
String reversed = TEXT.chars()
.mapToObj(c -> (char)c).reduce("", (s,c) -> c+s, (s1,s2) -> s2+s1);

System.out.println(reversed);
//Easy way
//using the String Builder class
String reversedString=new StringBuilder(TEXT).reverse().toString();
System.out.println(reversedString);

//Other way String to chars and then append to reverse builder


StringBuilder reverseStr = new StringBuilder();
char[] charsArr=TEXT.toCharArray();

for(int i=0;i<charsArr.length;i++){
reverseStr.insert(i,charsArr[charsArr.length-1-i]);
}
System.out.println(reverseStr);

if(reversed.equals(reverseString.toString())&&
reversedString.equals(reverseStr.toString())){
System.out.println("Reverse is done");
}

private static void displayExecutionTime(long time) {


System.out.println("Execution time: " + time + " ns" + " (" +
TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS) + " ms)");
}

You might also like