Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
sample java interview question
package com.learning;
import java.util.Arrays;
import java.util.stream.Collectors;
/**
* Created by sargonbenjamin on 5/3/20.
*/
public class ReverseWordCharsInSentence {
public static void main(String args[]){
System.out.println(solveProblem("Hi my name is ABCD"));
System.out.println(solveProblemByStreams("Hi my name is ABCD"));
}
public static String solveProblem(String input){
if(input == null || input.isEmpty())return input;
//split or java StringTokenizer is fine
String[] tokens = input.split(" ");
StringBuilder sb = new StringBuilder("");
for(String str : tokens){
sb.append(reverseString(str) + " ");
}
//remove the last space character
return sb.substring(0,sb.length()-1);
}
public static String solveProblemByStreams(String input){
return Arrays.stream(input.split(" "))
.map(ReverseWordCharsInSentence::reverseString)
.collect( Collectors.joining(" ") );
}
/**
* reverse string by only looping through half the characters
* this optimization is not necessary
* @param input
* @return
*/
public static String reverseString(String input){
if(input == null || input.isEmpty()) return input;
char[] charArr = input.toCharArray();
for(int i = 0; i<charArr.length/2; i++){
char temp = charArr[i];
charArr[i] = charArr[charArr.length-1-i];
charArr[charArr.length-1-i] = temp;
}
return new String(charArr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment