Way too long words - java

This is my solution to the "way too long words" problem on codeforces.
Even though I am getting correct output, but still it has been reported as the wrong answer to a question by codeforces.
https://codeforces.com/problemset/problem/71/A
(link to the question)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//charAt() is an inbuilt method which can read a string letter by letter
Scanner input=new Scanner(System.in);
int n;
//System.out.println("how many words do you wish to enter?");
n=input.nextInt();
String[] words=new String[n+1];
for(int i=0;i<n+1;i++)
{
words[i]=input.nextLine();
}
for(int j=0;j<n+1;j++)
{
if(words[j].length()<10)
{
System.out.print(words[j]);
}
else
{
System.out.print(words[j].charAt(0));
System.out.print(words[j].length()-2);
System.out.print(words[j].charAt(words[j].length()-1));
}
System.out.print("\n");
}
}
}

Problem is with the condition, you are only skipping words below the length of 10 but not considering the words with exact of 10 length.
if(words[j].length()<=10)
{
System.out.print(words[j]);
}
Change the condition it should work.

Inside the for loop for int j do something like this -
if(words[j].length()<=10) //boundary check
{
System.out.print(words[j]);
}
else
{
System.out.println(words[j].charAt(0).toString() + words[j].length()-2 + words[j].charAt(words[j].length()-1).toString());
}

Because where r you entering string in your program. Once you run, you will get to know.
Btw this is the solution of actual problem.
public static void main(String[] args){
String str=null;
int count=0;
Scanner scanner= new Scanner(System.in);
System.out.println("enter string :");
str=scanner.nextLine();
for(int i=0; i<str.length(); i++) {
count ++;
}
char first=str.charAt(0);
char last=str.charAt(count-1);
int num=count-2;
System.out.println("abbreviation is :" +first+num+last);
}

#include<iostream>
#include<string>
#include<sstream>
using namespace std;
string change_abb(string str)
{
string result;
if(str.length()>10)
{
int k=str.length()-2;
stringstream ss;
ss<<k;
string s;
ss>>s;
result+=str[0];
result+=s;
result+=str[str.length()-1];
}
else
{
result=str;
}
return result;
}
int main()
{
string in_str;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>in_str;
cout<<change_abb(in_str)<<endl;
}
}

Here is my answer in Python 3 (Answer accepted by Codeforces)
n = int(input())
p=""
for i in range(n):
s = input()
if len(s)>10:
p = s[0]+str((len(s)-2))+s[len(s)-1]
else:
p=s
print(p)

Related

How to use a loop to capitalize first occurring lowercase letter of string Java

Prompt: Use a loop to find the first occurring lowercase letter in the input string.
Then capitalize ONLY the lowercase letter you found, and then re-combine it with the rest of the string.
I'm so confused because one I don't know the exact number of indexes because it varies and two how can I capitalize only the first occurring lowercase. For example inputs are like BYus where I'm only supposed to capitalize the u. I have
public class PasswordImprover {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String userInput;
userInput = sc.next();
int userLowerCase = userInput.indexOf(".*[a-z].*");
for (int i = 0; i < userInput.length(); i++) {
if (Character.isLowerCase(userInput.charAt(i))) {
System.out.print(userInput.toUpperCase().charAt(i));
} else if (!userInput.contains(".*[a-z].*")) {
System.out.print(userInput.charAt(i));
}
}
}
}
but this just outputs everything in uppercase. Please help.
Get rid of that regex and just use a simple loop and a flag to indicate that you have process the first LC char
Scanner sc = new Scanner(System.in);
String userInput= sc.next();
boolean done = false;
for (int i = 0; i < userInput.length(); i++) {
if (!done && Character.isLowerCase(userInput.charAt(i))) {
System.out.print(userInput.toUpperCase().charAt(i));
done = true;
}
else {
System.out.print(userInput.charAt(i));
}
}
I'm so confused because one I don't know the exact number of indexes because it varies
Yes, that would the reason for the loop
how can I capitalize only the first occurring lowercase
Well, there's a few ways you might do it. String#substring might be starting point, for example...
public class Test {
public static void main(String[] args) {
String test = "BYus";
StringBuilder sb = new StringBuilder(test);
for (int index = 0; index < sb.length(); index++) {
if (Character.isLowerCase(sb.charAt(index))) {
test = test.substring(0, index) + Character.toUpperCase(test.charAt(index)) + test.substring(index + 1);
break;
}
}
System.out.println(test);
}
}
or, if you want to be a little more efficient, you could use a StringBuilder, for example...
public class Test {
public static void main(String[] args) {
String test = "BYus";
StringBuilder sb = new StringBuilder(test);
for (int index = 0; index < sb.length(); index++) {
if (Character.isLowerCase(sb.charAt(index))) {
sb.replace(index, index + 1, Character.toString(test.charAt(index)).toUpperCase());
break;
}
}
test = sb.toString();
System.out.println(test);
}
}
You could also convert the String to a character array and simply replace the first lower cased character in it and build a new String at the end, for example...
public class Test {
public static void main(String[] args) {
String test = "BYus";
char[] characters = test.toCharArray();
for (int index = 0; index < characters.length; index++) {
if (Character.isLowerCase(characters[index])) {
characters[index] = Character.toUpperCase(test.charAt(index));
break;
}
}
test = new String(characters);
System.out.println(test);
}
}
So, you know, options
You can iterate over the input as an array of chars:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string ");
char[] userInput = sc.next().toCharArray();
for (int i = 0; i < userInput.length; i++) {
if (Character.isLowerCase(userInput[i])) {
userInput[i] = Character.toUpperCase(userInput[i]);
break;
}
}
System.out.println(String.valueOf(userInput));
}
An example for regex.
String str = "BYus";
str = str.replaceFirst("([^a-z]*.).*", "$1").toUpperCase() + str.replaceFirst("[^a-z]*.(.*)", "$1");
System.out.println(str); //BYUs

how to replace an integer array with characters in java

int = 0111254
replace all 0 with 'z'
replace odd integers with 'p'
replace even integers with 'q'
The output should be zpppqpq
My part of the code....
public static void main(String[] args) {
int num;
Scanner sc=new Scanner(System.in);
num=sc.nextInt();
int temp;
int b[]=new int[10];
char a[]=new char[10];
for(int i=0;i<b.length;i++) {
while(num!=0)
{
temp=num%10;
b[i]=temp;
num=num/10;
}
}
for(int i=0;i<b.length;i=i+2)
{
if(b[i]==0)
{
b[i]=115;
}
else if(b[i]%2!=0)
{
b[i]=113;
}
else if(b[i]%2==0) {
b[i]=112;
}
}
for(int i=0;i<a.length;i++)
{
a[i]=(char)b[i];
}
for(int i:a)
{
System.out.print((char)i);
}
it gives a wrong output of q s s s s
You could turn that integer into a string and then use String.replace().
String numberString = ""+0111254;
// Replace all 0 chars with z
numberString.replace('0','z');
// etc...
you can take the numbers into a string and then convert strings into an array, and by using a for loop, take the single number and parse into integer, then apply your logic.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] ary = String.valueOf(sc.next()).split("");
StringBuilder answer = new StringBuilder();
for (String n : ary) {
int value = Integer.parseInt(n);
if (value == 0) {
answer.append("z");
} else if (value % 2 == 0) {
answer.append("q");
} else {
answer.append("p");
}
}
System.out.print(answer.toString());
}

find a substring which is palindrome in given string

input is :levelmm
output is: the given string is palindrome because the given string contains level is a palindrome remain character like mm is neglected.
package example;
import java.util.Scanner;
public class exp2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("enter the string");
Scanner scan=new Scanner(System.in);
String s=scan.nextLine();
String t="";
String s1=s.substring(0, s.length()-1);
for(int i=s1.length()-1;i>=0;i--)
{
t=t+s.charAt(i);
}
if(t.equalsIgnoreCase(s1))
{
int count=t.length();
System.out.println("is palindrome"+(count-1));
}else
{
System.out.println("not a palindrome");
}
}
}
but its not working completely..
First of all, the line String s1 = s.substring(0, s.length() - 1); removes one character from your word, which is not something that looks like it's supposed to happen.
What it looks like is that you want to create every possible substring of an input and see if that is a palindrome. To see whether something is a palindrome I propose this:
private static boolean isPalindrome(String word) {
String reverseWord = "";
for (int i = word.length() - 1; i > -1; i--) {
reverseWord += word.toCharArray()[i];
}
return reverseWord.equalsIgnoreCase(word);
}
Getting every single substring is more difficult, but can be done like this:
private static String[] allSubstrings(String word) {
int amount = 0;
for (int i = 0; i < word.length() + 1; i++) {
amount += i;
}
String[] res = new String[amount];
int index = 0;
for (int i = 0; i < word.length(); i++) {
for (int j = i + 1; j < word.length() + 1; j++) {
res[index] = word.substring(i, j);
index++;
}
}
return res;
}
Now, since every word that is 1 long is a palindrome, we don't want that, so in the main method we can say a word has to be more than 1 long. This results in a main method like this:
public static void main(String[] args) {
System.out.println("enter the string");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
boolean isPal = false;
for (String word : allSubstrings(s)) {
if (word.length() > 1 && isPalindrome(word)) {
isPal = true;
}
}
if (isPal) {
System.out.println("Is palindrome");
} else {
System.out.println("Is not palindrome");
}
}
I hope this answers your question and I wish you happy coding.

How do I make this output happen in java?

I'm a beginner and I want to output the following using a for loop and subscript and I'm not sure.
output:
Jamaica
amaica
maica
aica
ica
ca
a
What can I do, in order to achieve this output?
First: You need to loop for generating n line which is the length of array.
Second: You need to print the spaces with is same value as row - 1 number of times.
Second: You need to print character start from row - 1 number to the length of the string.
And the final solution will be:
public class MyClass {
public static void printStr(String str) {
int i,j;
for (i = 0; i < str.length();i++) {
for(j = 0; j < i; j++) {
System.out.print(" ");
}
for(j = i; j < str.length();j++) {
System.out.print(str.charAt(j));
}
System.out.println("");
}
}
public static void main(String args[]) {
MyClass.printStr("Jamaica");
}
}
I would use two regular expressions, the first to terminate the loop when the String is filled with white space. The second to replace the first non-white space character with a white space in the loop body (after printing the current String value). And, if it's possible the String might be empty you should guard against that. Like,
String s = "Jamaica";
if (!s.isEmpty()) {
while (!s.matches("\\s+")) {
System.out.println(s);
s = s.replaceFirst("\\S", " ");
}
}
Outputs (as requested)
Jamaica
amaica
maica
aica
ica
ca
a
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.next(); //input through scanner class
int len = s.length();
for(int i=0;i<len;i++){
for(int j=0;j<i;j++){
System.out.print(" ");
}
for(int j=i;j<len;j++){
System.out.print(s.charAt(j));
}
System.out.println("");
}
}
Hopefully that helps
Try following code:
StringBuilder country = new StringBuilder("Jamaica");
for(int i=0; i< country.length();i++){
if(i > 0)
{
for(int j=0;j<i;j++){
country.setCharAt(j,' ');
}
}
System.out.println(country);
}

Number of substrings of string which has three vowels

I participated in a coding challenge on hackerearth , and i was asked the following question .
Alice and Bob are playing a game in which Bob gives a string SS of length NN consisting of lowercase English alphabets to Alice and ask her to calculate the number of sub-strings of this string which contains exactly 3 vowels.
This is my code
import java.io.BufferedReader;
import java.io.InputStreamReader;
class TestClass1{
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
String stringArray[]=new String[N];
for (int i = 0; i < N; i++) {
int len = Integer.parseInt(br.readLine());
stringArray[i]=br.readLine();
}
for (int i = 0; i < N; i++) {
System.out.println(determineNumberOfSubstring(stringArray[i]));
}
}
public static int determineNumberOfSubstring(String str)
{
int numberOfSubstring=0;
for(int i=0;i<str.length();i++)
{
int ctr=0;
for(int j=1;j<str.length()-i;j++)
{
String subString = str.substring(i,i+j);
if(subString.length()<3)
{
continue;
}
if(subString.contains("a")||subString.contains("e")||subString.contains("i")||subString.contains("o")||subString.contains("u")
||subString.contains("A")||subString.contains("E")||subString.contains("I")||subString.contains("O")||subString.contains("U"))
{
ctr+=3;
}
}
if(ctr==3){
numberOfSubstring++;
}
}
return numberOfSubstring;
}
}
Iam getting time limit exceeded for the above code . Could any one help me out on how to optimise it .
Update1
Code as per #GhostCat logic , this needs to be tested and is not the final code.
class TestClass1{
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
String stringArray[]=new String[N];
for (int i = 0; i < N; i++) {
int len = Integer.parseInt(br.readLine());
stringArray[i]=br.readLine();
}
for (int i = 0; i < N; i++) {
System.out.println(determineNumberOfSubstring(stringArray[i]));
}
}
public static int determineNumberOfSubstring(String str)
{
int numberOfSubstring=0;
int ctr=0;
int subStringStart=0;
Stack<String> s = new Stack<String>();
for(int i=0;i<str.length();i++)
{
if(isVowel(str.charAt(i)))
ctr++;
if(ctr==3)
{
numberOfSubstring++;
ctr=0;
if(s.empty())
s.push(str.substring(0,i));
else
s.push(new String(s.peek().substring(1,i+1)));
i=str.indexOf(s.peek().charAt(1))-1;
}
}
return numberOfSubstring;
}
private static boolean isVowel(char c) {
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'
||c=='A'||c=='E'||c=='I'||c=='O'||c=='U')
return true;
return false;
}
}
Hint: your code is iterating the whole substring for each and any lower and upper case vowel there is. And that happens in a loop in a loop.
Instead: use ONE loop that goes over the characters of the input string. And then check each position if it is a vowel by checking against a set of characters (containing those valid vowels). The final thing you need: a simple "sliding" window; like: when you spot three vowels, you can increase your counter; to then "forget" about the first of the three vowels you just found; like in:
a x e y i --> vowels a/e/i give one substring
x e y i ... and you look out for the next substring e/i/... now
Actual implementation is left as exercise to the reader ...
Long story short: this count can be computed by processing your input ONCE. Your code is iterating countless times more than once. Well, not countless, but N * N * some more.
( the one thing to be careful with: when using a Set<Character> be precise when you turn a char value into aCharacter object; you want to minimize the instances of that happening, too; as that is a rather expensive operation )
HAPPY CODING ###### (if useful then upvote)
Que: count possible substring contain exactly 3 vowel in given string
my approach in O(n):
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>>s;
vector<long long int>idex;
idex.push_back(-1);
for(int i=0;i<n;i++)
{
if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u')
{
idex.push_back(i);
}
}
idex.push_back(n);
if(idex.size()<5)
{
cout<<0<<endl;
}
else
{
long long int ans=0;
for(int i=1;i<=idex.size()-4;i++)
{
ans+=(idex[i]-idex[i-1])*(idex[i+3]-idex[i+2]);
}
cout<<ans<<endl;
}
}

Categories

Resources