Expand string broken up into repeated, nested components [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm working on a problem, where given a string with substrings in paranthesis followed by values in curly brackets, the string expands by repeating the substring that number of times. So if you had (ab(d){3}){2} you'd get abdddabddd.
I feel like Im on the right track but that 1. this is pretty inefficient and 2. the tests seem to not return. Would love some help!
public class ExpandedString {
public static String expandedString(String inputStr) {
while (inputStr.contains("(")) {
for (int i = 0; i < inputStr.length(); i++) {
//check if there's something to repeat
if (inputStr.charAt(i) == '{') {
int temp = i;
//find what you need to repeat
while (inputStr.charAt(temp) != '(') {
temp--;
}
String inputStr2 = inputStr.substring(i);
int numTimes = i + inputStr.indexOf("}");
//replace (blah) with blah times repeated numTimes
StringBuilder repeated = new StringBuilder();
for(int j = 0; j<numTimes;j++) {
repeated.append(inputStr.substring(temp + 1, i - 1));
}
inputStr.replace(inputStr.substring(temp, i), repeated.toString());
//start again
i = 0;
}
}
}
return inputStr;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// input for inputStr
String inputStr = in .nextLine();
String result = expandedString(inputStr);
System.out.print(result);
}
}

Here is a solution that uses a stack of StringBuilders and a current StringBuilder.
When a ( is read, the current StringBuilder is pushed onto the stack and a new StringBuilder is created.
When a ) is read, the multiplier mul is extracted, and the value of the current StringBuilder is appended mul times to the StringBuilder popped from the stack.
Otherwhise, append the char to the current StringBuilder.
import java.util.Stack;
public class Expand
{
public static String expand(String pattern)
{
StringBuilder sb = new StringBuilder();
Stack<StringBuilder> stack = new Stack<StringBuilder>();
int len = pattern.length();
int i = 0;
while(i<len)
{
char c = pattern.charAt(i);
if(c=='(')
{
stack.push(sb);
sb = new StringBuilder();
}
else if(c==')')
{
String s = sb.toString();
int k = pattern.indexOf('}', i);
int mul = Integer.parseInt(pattern.substring(i+2, k));
sb = stack.pop();
for(int j=0;j<mul;j++)
sb.append(s);
i = k;
}
else
sb.append(c);
i++;
}
return sb.toString();
}
public static void main(String[] args)
{
System.out.println(expand("(ab(d){3}){2}"));
}
}
Output:
abdddabddd

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###########

Pallindrome String is replaced by * character [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
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);
}

How to reverse words in string in java without using split and stringtokenizer [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to reverse words in string of java without using split method and StringTokenizer.
For example, How are you must be printed in you are How.
I tried but I failed to do it.
Any help will be appreciated.
Try below code snippet
import java.util.ArrayList;
public class ReverseString
{
public static void main(String args[])
{
String myName = "Here we go";
ArrayList al = new ArrayList();
al = recursiveReverseMethod(myName,al);
al.trimToSize();
StringBuilder sb = new StringBuilder();
for(int i = al.size()-1; i>=0;i--)
{
sb.append(al.get(i)+" ");
}
System.out.println(sb);
}
public static ArrayList recursiveReverseMethod(String myName,ArrayList al)
{
int index = myName.indexOf(" ");
al.add(myName.substring(0, index));
myName = myName.substring(index+1);
if(myName.indexOf(" ")==-1)
{
al.add(myName.substring(0));
return al;
}
return recursiveReverseMethod(myName,al);
}
}
Here is another flavor based on the old time logic of String reversal in 'C'., from this thread.,
class testers {
public static void main(String[] args) {
String testStr="LongString";
testers u= new testers();
u.reverseStr(testStr);
}
public void reverseStr(String testStr){
char[] d= testStr.toCharArray();
int i;
int length=d.length;
int last_pos;
last_pos=d.length-1;
for (i=0;i<length/2;i++){
char tmp=d[i];
d[i]=d[last_pos-i];
d[last_pos-i]=tmp;
}
System.out.println(d);
}
}
I would do this:
public static String reverseWordsWithoutSplit(String sentence){
if (sentence == null || sentence.isEmpty()) return sentence;
int nextSpaceIndex = 0;
int wordStartIndex = 0;
int length = sentence.length();
StringBuilder reversedSentence = new StringBuilder();
while (nextSpaceIndex > -1){
nextSpaceIndex = sentence.indexOf(' ', wordStartIndex);
if (nextSpaceIndex > -1) reversedSentence.insert(0, sentence.substring(wordStartIndex, nextSpaceIndex)).insert(0, ' ');
else reversedSentence.insert(0, sentence.subSequence(wordStartIndex, length));
wordStartIndex = nextSpaceIndex + 1;
}
return reversedSentence.toString();
}

Categories

Resources