Pallindrome String is replaced by * character [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Input a string which contains some palindrome substrings. Find out the position of palindrome substrings if exist and replace it by *. (For example if input string is “bob has a radar plane” then it should convert in “** has a ***** plane”.
My code is given below.
import java.util.Scanner;
public class Pallindrome_String {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
String sen;
System.out.println("Enter the String: ");
sen = in.nextLine();
pallindrome(sen);
in.close();
}
public static void pallindrome(String s) {
int len = s.length();
for (int i = 0; i < len; i++) {
String res = "";
if (s.charAt(i) == ' ') {
res = s.substring(0, i);
String rev = "";
for (int j = res.length() - 1; j >= 0; j--) {
rev = rev + res.charAt(i);
}
if (rev.equals(res)) {
rev = "*";
System.out.print(rev + " ");
} else {
System.out.print(res + " ");
}
}
}
}
}

There is a simpler, more efficient way of finding palindromes in Java. I'll explain the steps to implementing it.
first, after getting your input 'sen', you can use the split method of the String class to seperate each word.
sen = in.nextLine();
String[] splitted = s.split(" "); // seperates the string when there is a whitespace and stores the resulting words in an array
After you've got the words in an array, you can check each word and see if its a palindrome. To do so, you can read the word front to back and back to front and compare the result.
If u find a palindrome, store its index (position in the 'splitted' array). After you've gone through all the words in the 'splitted' array, you can then print out the appropriate number of *'s based on the length of the word.

The split() will loose double spaces and punctuation in source string and make a lot of useless objects in memory. This is more correct solution. IMHO
public static void main(String[] args) {
String s = "Bob! Do you have a radar plane?";
StringBuilder sb = new StringBuilder(s);
Matcher m = Pattern.compile("[a-zA-Z]+").matcher(s);
while (m.find()) {
String word = m.group();
if (word.length() == 0)
continue;
String reversed = new StringBuffer(word).reverse().toString();
if (word.equalsIgnoreCase(reversed)) {
StringBuilder replacement = new StringBuilder();
for (int i = 0; i < word.length(); i++)
replacement.append('*');
sb.replace(m.start(), m.end(), replacement.toString());
}
}
System.out.println(sb);
}

Related

How to count number of character Occurrences inside a string and replace selected character with the counts [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 20 days ago.
Improve this question
My task is to find number of occurrences of a string character and replace the character with the number of occurrence up to that particular index inside the string
public static void main(String[] args) {
char[] arr = "hello".toCharArray();
arr[2] = '1';
arr[3] = '2';
System.out.println(arr);
}
Output should be: he12o
I know we cant reuse this approach.
what is the output of "helololol"?
output for helololol, ch='l' , then the output should be he1o2o3o4; if ch='o' then output should be hel1l2l3l
If according to this rule, Can be achieved with a loop:
public static void main(String[] args) {
char flag = 'l';
String str = "hellollololollol";
int num = 1;
for(int i = 0, len = str.length(); i < len; i++) {
if (str.charAt(i) == flag) {
str = str.substring(0, i) + num++ + str.substring(i + 1);
}
}
System.out.println(str);
}
Note that if the number of specified characters exceeds 9, it will look weird, If the number of characters exceeds 9, special processing is required:
public static void main(String[] args) {
char flag = 'l';
String str = "hellollololollollol";
int num = 1;
for(int i = 0, len = str.length(); i < len; i++) {
if (str.charAt(i) == flag) {
str = str.substring(0, i) + num++ + str.substring(i + 1);
if (num > 10) {
len++;
}
}
System.out.println(str);
}
}
The same problem, if the number of characters exceeds 100, 1000, 10000, special processing is required, because the length of the number added to the string is one bit longer than the original character, how to deal with it flexibly, you need to think about it yourself!
Instead of using primitive methods to manipulate string , we can use the following to have clean code .
public static void main(String args[]) {
String str="helolololololololololololololololololololololololololololololololololololo";
String checkString="l";
int count=1;
StringBuilder sb=new StringBuilder();
List<String> strLst= new ArrayList<String>();
for(int i=0;i<str.length();i++) {
strLst.add(String.valueOf(str.charAt(i)));
}
for(String x : strLst) {
if(x.equals(checkString)) {
sb.append(count);
count++;
}else {
sb.append(x);
}
}
System.out.println(sb);
}
The output for the above string will be
he1o2o3o4o5o6o7o8o9o10o11o12o13o14o15o16o17o18o19o20o21o22o23o24o25o26o27o28o29o30o31o32o33o34o35o36o
With this implementation , we don't have to worry about splitting the string using substring and checking their index .Will work for 'n' number of repetitive letters.

How to find most common used number in users input? Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How could an user input their numbers, for example : "122113333443" and I needed to output "3333".
If they again input something like "1224" I then needed to output "22".
How would this be possible if I don't know which numbers they are going to input and how the code would look like?
So far I only have the beginning, which shows input output error if the input aren't numbers.
int k;
Scanner sc = new Scanner(System.in);
System.out.println("input string:");
if (sc.hasNextInt())
k = sc.nextInt();
else {
System.out.println("input-output error");
sc.close();
return;
}
You can use a variable (StringBuilder longest in the code given below) to keep track of the longest sequence of characters having the same characters.
Iterate all characters of the string and keep appending the characters to a StringBuilder (StringBuilder sb in the code given below) until a different character is found. When this happens, reset the sb.
After each append to the sb, check if its length has become bigger than that of longest. If yes, transfer the content of the StringBuilder to longest.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Input string: ");
String input = sc.nextLine();
System.out.println(getLongest(input));
}
static String getLongest(String str) {
StringBuilder sb = new StringBuilder();
StringBuilder longest = new StringBuilder();
char current = 0;
// Process all but the last character of str
for (int i = 0; i < str.length() - 1; i++) {
current = str.charAt(i);
sb.append(current);
if (sb.length() > longest.length()) {
longest = new StringBuilder(sb);
}
if (current != str.charAt(i + 1)) {
sb = new StringBuilder();
}
}
// Process the last character of str
sb.append(str.charAt(str.length() - 1));
if (sb.length() > longest.length()) {
longest = new StringBuilder(sb);
}
return longest.toString();
}
}
A sample run:
Input string: 122113333443
3333
Another sample run:
Input string: 1224
22
This is Java not JavaScript, wrong tag. However, heres my shot. I am not that good with java but anyway:
public String findMostCommon(int inp) {
int[] occuranceTable = new int[9];
for (int i = 0; i < occuranceTable.length; i++) {
occuranceTable[i] = 0;
}
// Convert input int to Array of digits
String temp = Integer.toString(inp);
int[] digits = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
digits[i] = temp.charAt(i) - '0';
}
// Get Occurances of each digit
for(int digit : digits) {
occuranceTable[digit]++;
}
// Find most frequent digit
int max = -1;
for (int i = 0; i < occuranceTable.length; i++) {
max = occuranceTable[i] > max ? i : max;
}
// Make result string
String result = "";
for (int i = 0; i < occuranceTable[max]; i++)
result += String.valueOf(max);
return result;
}

Guessing symbols in a Sting word java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Got a String like:
String str = "###############";
Got guess word, for example:
String guess = "Java"
User must guess word:
User input:
Sava
Sring should be:
String str = "#a#a###########";
all right symbols placed on their indexes
String is immutable class.
I chose Stringbuilder
for (int i = 0; i < length ; i++) {
if (rnd.charAt(i) == guess.charAt(i) && rnd.charAt(i) != '#'){
sb.append(rnd.charAt(i));
}
}
System.out.println(sb);
sb.delete(0, sb.length());
Stringbuilder add right symbols not on possition 'i', but on the last indexes.
Example:
guess word: Java
user input Sala:
System.out.println(sb);
###############aa
How I can achieve needed result?
And what tools should I use?
needed result:
Example:
guess word Java:
user input Sala:
System.out.println(sb);
#a#a###########
Work like this:
private static String word(){
String guess = new Scanner(System.in).nextLine();
return guess;
}
private static void guessWord(String[]arr) {
int random = new Random().nextInt(arr.length);
String rnd = arr[random];
int length = 15;
StringBuilder sb = new StringBuilder();
String guess = "";
int rndLength = length - rnd.length();
int guessLength = length - guess.length();
do {
System.out.println("Enter a word: ");
guess = word();
if (sb.length() < length){
for (int i = 0; i < length ; i++) {
sb.append("#");
}
}
for (int i = 0; i < length && i < rnd.length() && i < guess.length(); i++) {
if (rnd.charAt(i) == guess.charAt(i)){
sb.setCharAt(i, rnd.charAt(i));
sb.delete(length, sb.length());
}
}
if (rnd.equals(guess)){
System.out.println("Guess word: " + rnd);
break;
}else if (!rnd.equals(guess)) {
System.out.println(sb);
}
}while (!rnd.equals(guess));
}
You can do it as follows:
public class Main {
public static void main(String[] args) {
String str = "#a#a###########";
String guess = "Java";
String input = "Sala";
StringBuilder sb = new StringBuilder();
int i;
for (i = 0; i < str.length() && i < guess.length() && i < input.length(); i++) {
// In case of a match, append the matched character
if (guess.charAt(i) == input.charAt(i)) {
sb.append(guess.charAt(i));
} else {// Else append the placeholder symbol from `str`
sb.append(str.charAt(i));
}
}
// Append the remaining placeholder characters from `str`
sb.append(str.substring(i));
// Display
System.out.println(sb);
}
}
Output:
#a#a###########

Recursively computing all possible permutations of a string Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to compute all possible permutations of a given string using recursion in Java. However, I don't know what's wrong with my code.
Here's my algorithm:
public static ArrayList<String> computeAllPossiblePermutations(String str) {
ArrayList<String> perms = new ArrayList<>();
//base case
if (str.length() == 1)
perms.add(str);
else {
//loop over the string
for (int i = 0; i < str.length() - 1; i++) {
//make a subset of the string excluding the first char
String sub = str.substring(i + 1, str.length());
//compute permutations of the subset
ArrayList<String> subPerms = computeAllPossiblePermutations(sub);
//add the first char that we excluded at the start of each permutations
for (String s : subPerms) {
s = str.charAt(i) + s;
perms.add(s);
}
}
}
return perms;
}
There are a few issues:
The following line: String sub = str.substring(i+1, str.length()); ignores the first character
The same line also treats anything after index i as a "block" of substring that is left unchanged, while in order to generate permutation we should insert the current (first) character in between any two characters of the rest of the string - and do that for each permutation
The line s = str.charAt(i) + s; repeats the same mistake in #2
Here's a suggested fix:
public static ArrayList<String> computeAllPossiblePermutations(String str) {
ArrayList<String> perms = new ArrayList<>();
if (str.length() == 1) {
perms.add(str);
} else {
String chr = str.substring(0,1);
String rest = str.substring(1);
ArrayList<String> subPerms = computeAllPossiblePermutations(rest);
for (String s : subPerms) {
for (int j = 0; j <= s.length(); j++) {
String newPerm = s.substring(0,j) + chr + s.substring(j);
perms.add(newPerm);
}
}
}
return perms;
}

Reversing characters in each word in a sentence - Stack Implementation

This code is inside the main function:
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence");
String sentence = input.next();
Stack<Character> stk = new Stack<Character>();
int i = 0;
while (i < sentence.length())
{
while (sentence.charAt(i) != ' ' && i < sentence.length() - 1)
{
stk.push(sentence.charAt(i));
i++;
}
stk.empty();
i++;
}
And this is the empty() function:
public void empty()
{
while (this.first != null)
System.out.print(this.pop());
}
It doesn't work properly, as by typing example sentence I am getting this output: lpmaxe. The first letter is missing and the loop stops instead of counting past the space to the next part of the sentence.
I am trying to achieve this:
This is a sentence ---> sihT si a ecnetnes
Per modifications to the original post, where the OP is now indicating that his goal is to reverse the letter order of the words within a sentence, but to leave the words in their initial positions.
The simplest way to do this, I think, is to make use of the String split function, iterate through the words, and reverse their orders.
String[] words = sentence.split(" "); // splits on the space between words
for (int i = 0; i < words.length; i++) {
String word = words[i];
System.out.print(reverseWord(word));
if (i < words.length-1) {
System.out.print(" "); // space after all words but the last
}
}
Where the method reverseWord is defined as:
public String reverseWord(String word) {
for( int i = 0; i < word.length(); i++) {
stk.push(word.charAt(i));
}
return stk.empty();
}
And where the empty method has been changed to:
public String empty() {
String stackWord = "";
while (this.first != null)
stackWord += this.pop();
return stackWord;
}
Original response
The original question indicated that the OP wanted to completely reverse the sentence.
You've got a double-looping construct where you don't really need it.
Consider this logic:
Read each character from the input string and push that character to the stack
When the input string is empty, pop each character from the stack and print it to screen.
So:
for( int i = 0; i < sentence.length(); i++) {
stk.push(sentence.charAt(i));
}
stk.empty();
I assume that what you want your code to do is to reverse each word in turn, not the entire string. So, given the input example sentence you want it to output elpmaxe ecnetnes not ecnetnes elpmaxe.
The reason that you see lpmaxe instead of elpmaxe is because your inner while-loop doesn't process the last character of the string since you have i < sentence.length() - 1 instead of i < sentence.length(). The reason that you only see a single word is because your sentence variable consists only of the first token of the input. This is what the method Scanner.next() does; it reads the next (by default) space-delimited token.
If you want to input a whole sentence, wrap up System.in as follows:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
and call reader.readLine().
Hope this helps.
Assuming you've already got your input in sentence and the Stack object is called stk, here's an idea:
char[] tokens = sentence.toCharArray();
for (char c : tokens) {
if (c == ' ') {
stk.empty();
System.out.print(c);
} else {
stk.add(c);
}
}
Thus, it will scan through one character at a time. If we hit a space character, we'll assume we've hit the end of a word, spit out that word in reverse, print that space character, then continue. Otherwise, we'll add the character to the stack and continue building the current word. (If you want to also allow punctuation like periods, commas, and the like, change if (c == ' ') { to something like if (c == ' ' || c == '.' || c == ',') { and so on.)
As for why you're only getting one word, darrenp already pointed it out. (Personally, I'd use a Scanner instead of a BufferedReader unless speed is an issue, but that's just my opinion.)
import java.util.StringTokenizer;
public class stringWork {
public static void main(String[] args) {
String s1 = "Hello World";
s1 = reverseSentence(s1);
System.out.println(s1);
s1 = reverseWord(s1);
System.out.println(s1);
}
private static String reverseSentence(String s1){
String s2 = "";
for(int i=s1.length()-1;i>=0;i--){
s2 += s1.charAt(i);
}
return s2;
}
private static String reverseWord(String s1){
String s2 = "";
StringTokenizer st = new StringTokenizer(s1);
while (st.hasMoreTokens()) {
s2 += reverseSentence(st.nextToken());
s2 += " ";
}
return s2;
}
}
public class ReverseofeachWordinaSentance {
/**
* #param args
*/
public static void main(String[] args) {
String source = "Welcome to the word reversing program";
for (String str : source.split(" ")) {
System.out.print(new StringBuilder(str).reverse().toString());
System.out.print(" ");
}
System.out.println("");
System.out.println("------------------------------------ ");
String original = "Welcome to the word reversing program";
wordReverse(original);
System.out.println("Orginal Sentence :::: "+original);
System.out.println("Reverse Sentence :::: "+wordReverse(original));
}
public static String wordReverse(String original){
StringTokenizer string = new StringTokenizer(original);
Stack<Character> charStack = new Stack<Character>();
while (string.hasMoreTokens()){
String temp = string.nextToken();
for (int i = 0; i < temp.length(); i ++){
charStack.push(temp.charAt(i));
}
charStack.push(' ');
}
StringBuilder result = new StringBuilder();
while(!charStack.empty()){
result.append(charStack.pop());
}
return result.toString();
}
}
public class reverseStr {
public static void main(String[] args) {
String testsa[] = { "", " ", " ", "a ", " a", " aa bd cs " };
for (String tests : testsa) {
System.out.println(tests + "|" + reverseWords2(tests) + "|");
}
}
public static String reverseWords2(String s) {
String[] sa;
String out = "";
sa = s.split(" ");
for (int i = 0; i < sa.length; i++) {
String word = sa[sa.length - 1 - i];
// exclude "" in splited array
if (!word.equals("")) {
//add space between two words
out += word + " ";
}
}
//exclude the last space and return when string is void
int n = out.length();
if (n > 0) {
return out.substring(0, out.length() - 1);
} else {
return "";
}
}
}
This can pass in leetcode

Categories

Resources