Strings Programs Expl
Strings Programs Expl
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:
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));
int cp = chs.entrySet().stream()
.filter(e -> e.getValue() == 1L)
.findFirst()
.map(Map.Entry::getKey)
.orElse(Integer.valueOf(Character.MIN_VALUE));
/**
* 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>
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;
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
💕 � 🎼🎼🎼!";
programToReverseString();
checkPalindrome();
countAllCharacterCountString();
countACharcterFrequencyInSentence();
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();
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();
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();
displayExecutionTime(System.nanoTime()-startTimeV4);
System.out.println(Arrays.toString(duplicatesV4.entrySet().toArray()));
// or: duplicatesV4.forEach( (k, v) -> System.out.print(k + "="+ v + ", "));
}
// 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));
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);
}
//Traditional way get chars array and include that in the key if not
available and put value =1 and from then increament the value
// 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, Integer> frequency =
// str.chars()
// .mapToObj(c -> (char)c)
// .collect(Collectors.groupingBy(Function.identity(),
Collectors.summingInt(c -> 1)));
//Other ways using map.
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");
}
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");
}
}
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);
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");
}