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;
}
Related
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.
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
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###########
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);
}
I need to get a new string based on an old one and a lag. Basically, I have a string with the alphabet (s = "abc...xyz") and based on a lag (i.e. 3), the new string should replace the characters in a string I type with the character placed some positions forward (lag). If, let's say, I type "cde" as my string, the output should be "fgh". If any other character is added in the string (apart from space - " "), it should be removed. Here is what I tried, but it doesn't work :
String code = "abcdefghijklmnopqrstuvwxyzabcd"; //my lag is 4 and I added the first 4 characters to
char old; //avoid OutOfRange issues
char nou;
for (int i = 0; i < code.length() - lag; ++i)
{
old = code.charAt(i);
//System.out.print(old + " ");
nou = code.charAt(i + lag);
//System.out.println(nou + " ");
// if (s.indexOf(old) != 0)
// {
s = s.replace(old, nou);
// }
}
I commented the outputs for old and nou (new, but is reserved word) because I have used them only to test if the code from position i to i + lag is working (and it is), but if I uncomment the if statement, it doesn't do anything and I leave it like this, it keeps executing the instructions inside the for statmement for code.length() times, but my string doesn't need to be so long. I have also tried to make the for statement like below, but I got lost.
for (int i = 0; i < s.length(); ++i)
{
....
}
Could you help me with this? Or maybe some advices about how I should think the algorithm?
Thanks!
It doesn't work because, as the javadoc of replace() says:
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
(emphasis mine)
So, the first time you meet an 'a' in the string, you replace all the 'a's by 'd'. But then you go to the next char, and if it's a 'd' that was an 'a' before, you replace it once again, etc. etc.
You shouldn't use replace() at all. Instead, you should simply build a new string, using a StringBuilder, by appending each shifted character of the original string:
String dictionary = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder(input.length());
for (int i = 0; i < input.length(); i++) {
char oldChar = input.charAt(i);
int oldCharPositionInDictionary = dictionary.indexOf(oldChar);
if (oldCharPositionInDictionary >= 0) {
int newCharPositionInDictionary =
(oldCharPositionInDictionary + lag) % dictionary.length();
sb.append(dictionary.charAt(newCharPositionInDictionary));
}
else if (oldChar == ' ') {
sb.append(' ');
}
}
String result = sb.toString();
Try this:
Convert the string to char array.
iterate over each char array and change the char by adding lag
create new String just once (instead of loop) with new String passing char array.
String code = "abcdefghijklmnopqrstuvwxyzabcd";
String s = "abcdef";
char[] ch = s.toCharArray();
char[] codes = code.toCharArray();
for (int i = 0; i < ch.length; ++i)
{
ch[i] = codes[ch[i] - 'a' + 3];
}
String str = new String(ch);
System.out.println(str);
}
My answer is something like this.
It returns one more index to every character.
It reverses every String.
Have a good day!
package org.owls.sof;
import java.util.Scanner;
public class Main {
private static final String CODE = "abcdefghijklmnopqrstuvwxyz"; //my lag is 4 and I added the first 4 characters to
#SuppressWarnings("resource")
public static void main(String[] args) {
System.out.print("insert alphabet >> ");
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
char[] char_arr = s.toCharArray();
for(int i = 0; i < char_arr.length; i++){
int order = CODE.indexOf(char_arr[i]) + 1;
if(order%CODE.length() == 0){
char_arr[i] = CODE.charAt(0);
}else{
char_arr[i] = CODE.charAt(order);
}
}
System.out.println(new String(char_arr));
//reverse
System.out.println(reverse(new String(char_arr)));
}
private static String reverse (String str) {
char[] char_arr = str.toCharArray();
for(int i = 0; i < char_arr.length/2; i++){
char tmp = char_arr[i];
char_arr[i] = char_arr[char_arr.length - i - 1];
char_arr[char_arr.length - i - 1] = tmp;
}
return new String(char_arr);
}
}
String alpha = "abcdefghijklmnopqrstuvwxyzabcd"; // alphabet
int N = alpha.length();
int lag = 3; // shift value
String s = "cde"; // input
StringBuilder sb = new StringBuilder();
for (int i = 0, index; i < s.length(); i++) {
index = s.charAt(i) - 'a';
sb.append(alpha.charAt((index + lag) % N));
}
String op = sb.toString(); // output