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;
}
}
Related
import java.util.Scanner;
public class POD9 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String tito_has = sc.nextLine();
String tito_wants = sc.nextLine();
String remaining = "";
int strips = 0;
while(true){
String longest_common = getLongestCommonSubstring(tito_has,tito_wants);
strips++;
tito_has = tito_has.replaceAll(longest_common,"*");
remaining = remaining + longest_common;
if(remaining.length() == tito_wants.length()){
break;
}
}
System.out.println(strips-1);
}
public static String getLongestCommonSubstring(String str1, String str2){
int m = str1.length();
int n = str2.length();
int max = 0;
int[][] dp = new int[m][n];
int endIndex=-1;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(str1.charAt(i) == str2.charAt(j) && str1.charAt(i) != Character.valueOf('*'))
{
if(i==0 || j==0){
dp[i][j]=1;
}else{
dp[i][j] = dp[i-1][j-1]+1;
}
if(max < dp[i][j])
{
max = dp[i][j];
endIndex=i;
}
}
}
}
return str1.substring(endIndex-max+1,endIndex+1);
}
}
This is my code used to retrieve the minimum number of paper cuts that are needed to form string 2 from string 1. This is the solution to the problem: Paper Cut Problem
I approached the problem by finding the longest substring between what Tito wants and what he has.
Thereafter, I replace the found sequences with '' as the input will only have letters. Also, in the cases, say, it has: "abbap" and tito wants:"bbaap", then this gives 3 cuts a|bb|a|p and not
2 (found bb->remove it (cut 1)->got (aap) -> found aa(cut2)-> remove it-> found b). So using "" helps in not making wrong substrings match.
I am pretty sure that my approach will solve most of the test cases. But I am getting the TIMELIMIT error here.
Please help me find an optimum way to achieve this?
public class Solution {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int tc = Integer.parseInt(br.readLine());//I get Numberformat Exception here
for(int i=0;i<tc;i++) // Even if my inputs are on separate lines
{
String original = br.readLine();
palindrome(original);
}
}
public static void palindrome(String original)
{
String reverse="";
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
{
System.out.println(0);
}
else
{
char[] org = original.toCharArray();
int len = org.length;
int mid = len / 2;
if(len % 2 == 0)
{
char[] front = new char[mid];
char[] back = new char[mid];
for(int i=0;i<mid;i++)
{
front[i] = org[i];
}
int j=0;
for(int i=len-1;i>=mid;i--)
{
back[j] = org[i];
j++;
while(j > mid)
{
break;
}
}
change(front,back,mid);
}
else
{
char[] front = new char[mid];
char[] back = new char[mid];
for(int i=0;i<mid;i++)
{
front[i] = org[i];
}
int j=0;
for(int i=len-1;i>mid;i--)
{
back[j] = org[i];
j++;
while(j > mid)
{
break;
}
}
change(front,back,mid);
}
}
}
public static void change(char[] front,char[] back,int len)
{
int count =0;
for(int i =0;i<len;i++)
{
if(front[i] != back[i] )
{
count += (back[i] - front[i]);
}
}
System.out.println(count)
}
}
What i try to do here is get an input from the number of test cases say 3 in my first line followed by the test-cases themselves.
sample input :
3
abc
abcba
abcd
Now it has to check if the string is a palindrome if its so it ll print 0
else it breaks the string into two halves front and back and finds the minimum number of changes to make it a palidrome.
here i have also checked if its a odd or even length string if odd i have omitted the middle char.
By changes we can only change 'd' to 'b' not 'b' to 'd'
Once a letter has been changed to 'a', it can no longer be changed.
My code works fine for the above input but it doesnt for some other inputs i dont quiet understand why..
for instance if i give a custom test case as
5
assfsdgrgregedhthtjh
efasfhnethiaoesdfgv
ehadfghsdfhmkfpg
wsertete
agdsjgtukgtulhgfd
I get a Number Format Exception.
Your code works fine here, whithout NumberFormatException: http://ideone.com/QJqjmG
This may not solve your problem, but improves your code...
As first user input you are expecting an integer. You are parsing the String returned by br.readLine() and do not take care of the NumberFormatException parseInt(...) may throw.
Just imagine someone hits space or return key as first input.
So I propose to put a try-catch-block around the parseInt(...). Here is an example how this may look like.
Guys thank you for all your suggestion i just found out why my other test cases weren't working
public static void change(char[] front,char[] back,int len)
{
int count =0;
for(int i =0;i<len;i++)
{
if(front[i] != back[i] )
{
count += (back[i] - front[i]);
}
}
System.out.println(count)
}
This part of my code has to be changed to
public static void change(char[] front,char[] back,int len)
{
int count =0;
for(int i =0;i<len;i++)
{
if(front[i] != back[i] )
{
char great = findGreatest(front[i],back[i]);
if(great == back[i])
{
count += (back[i] - front[i]);
}
else
{
count += (front[i] - back[i]);
}
}
}
System.out.println(count);
}
public static char findGreatest(char first,char second)
{
int great = first;
if(first < second)
{
great = second;
}
return (char)great;
}
Because i get negative values coz of subtracting ascii's which are greater than them and as i have already mentioned i can only do 'd' to 'a' not the other way round.
Thank you for your time guys!
My Question is-
Input is string. Return true if the String has exactly 1 character that appears twice in the string, 0 character that appear thrice in the string, and at least 1 character that appear four or more times in the string. There is a problem in my code and I am unable to find out the problem.
public class CheckCharacterOccurence {
static String testcase1 = "jjiiiiyy";
public static void main(String[] args) {
CheckCharacterOccurence testInstance = new CheckCharacterOccurence();
boolean result = testInstance.checkCharacterOccurence(testcase1);
System.out.println(result);
}
public boolean checkCharacterOccurence(String str) {
char ch=' ';
char ch1=' ';
int temp=0;
int temp1=0;
int temp2=0;
int count=0;
for(int i=0;i<str.length();i++){
ch=str.charAt(i);
for(int j=i;j<str.length();j++){
if(str.charAt(i)==str.charAt(j)){
ch1=str.charAt(i);
count++;
}
}
System.out.println(count);
if(count==2&&ch!=ch1){
temp++;
}
if(count==3&&ch!=ch1){
temp1++;
}
if(count>=4){
temp2++;
}
count=0;
}
if(temp==1&&temp1==0&&temp2>=1){
return true;
}
return false;
}
}
I would suggest using a map
For all characters in string, increment map[that_char]
At last iterate over map to find how many times each character appeared.
Alternatively you can use array also to keep count.
Something like
int [] ctr = new int[256]
ctr = all zeroes
for (ch : string)
ctr[ch]++
mxocc = 0
maxch = 'a'
for(ch = a, b, c, d, e...)
if(ctr[ch] > maxocc) maxocc = ctr[ch] and maxch = ch
Output require info
hey you can figure out the problem ... atleast i can give to some extend same code , you can check it and try to solve your problem... This program finds the pattern in the string, now you can go through this program, and try to solve ur problem in your program by your own self.and try to do it by your own then only ur coding skills will get improved.and vote this answer if u fing it really helpful
#include<stdio.h>
#include<string.h>
int occur(char[],char[]);
int occur(char sent[],char pattern[])
{
int count=0;
for(int i=0,j=i;sent[i]!='\0';)
{
if(sent[i+j]==pattern[j]&&pattern[j]!='\0')
{
j++;
}
else if(j==strlen(pattern))
{
count++;
i=i+j;
j=0;
}
else
{
i++;
j=0;
}
}
return count;
}
int main()
{
char sent[] = "aabaabaaabbbabababddfggaabbbasab";
char pattern[] = "aba";
int result = occur(sent,pattern);
printf("\nNo of Occurrences --- > %d",result);
return 0;
}
You should simplify your code. For example there is not need to use those complex for-loops, you can use a for-each.
This code finds out the frequency of characters in a string and stores it in a Map.
import java.util.*;
public class CheckCharacterOccurence {
public static void main(String[] args) {
Map<Character, Integer> counting = new HashMap<Character, Integer>();
String testcase1 = "Helloooo";
for(char ch: testcase1.toCharArray()){
Integer freq = counting.get(ch);
counting.put(ch, (freq == null) ? 1 : freq + 1);
}
System.out.println(counting.size() + " distinct characters:");
System.out.println(counting);
}
}
I've been looking and I can't find anywhere how to write a word count using 3 methods. Here is what the code looks like so far. I'm lost on how to use the methods. I can do this without using different methods and just using one. Please help!!!
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter a string: ");
String s = in.nextLine();
if (s.length() > 0)
{
getInputString(s);
}
else
{
System.out.println("ERROR - string must not be empty.");
System.out.print("Enter a string: ");
s = in.nextLine();
}
// Fill in the body with your code
}
// Given a Scanner, prompt the user for a String. If the user enters an empty
// String, report an error message and ask for a non-empty String. Return the
// String to the calling program.
private static String getInputString(String s) {
int count = getWordCount();
while (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) == " ")
{
count ++;
}
}
getWordCount(count);
// Fill in the body
// NOTE: Do not declare a Scanner in the body of this method.
}
// Given a String return the number of words in the String. A word is a sequence of
// characters with no spaces. Write this method so that the function call:
// int count = getWordCount("The quick brown fox jumped");
// results in count having a value of 5. You will call this method from the main method.
// For this assignment you may assume that
// words will be separated by exactly one space.
private static int getWordCount(String input) {
// Fill in the body
}
}
EDIT:
I have changed the code to
private static String getInputString(String s) {
String words = getWordCount(s);
return words.length();
}
private static int getWordCount(String s) {
return s.split(" ");
}
But I can't get the string convert to integer.
You have read the name of the method, and look at the comments to decide what should be implemented inside the method, and the values it should return.
The getInputString method signature should be:
private static String getInputString(Scanner s) {
String inputString = "";
// read the input string from system in
// ....
return inputString;
}
The getWordCount method signature should be:
private static int getWordCount(String input) {
int wordCount = 0;
// count the number of words in the input String
// ...
return wordCount;
}
The main method should look something like this:
public static void main(String[] args) {
// instantiate the Scanner variable
// call the getInputString method to ... you guessed it ... get the input string
// call the getWordCount method to get the word count
// Display the word count
}
count=1 //last word must be counted
for(int i=0;i<s.length();i++)
{
ch=s.charAt(i);
if(ch==' ')
{
count++;
}
}
Use trim() and split() on 1-n whitespace chars:
private static int getWordCount(String s) {
return s.trim().split("\\s+").length;
}
The call to trim() is necessary, otherwise you'll get one extra "word" if there is leading spaces in the string.
The parameter "\\s+" is necessary to count multiple spaces as a single word separator. \s is the regex for "whitespace". + is regex for "1 or more".
What you need to do is, count the number of spaces in the string. That is the number of words in the string.
You will see your count will be off by 1, but after some pondering and bug hunting you will figure out why.
Happy learning!
You can do this by :
private static int getWordCount(String input) {
return input.split("\\s+").length;
}
Use String.split() method like :
String[] words = s.split("\\s+");
int wordCount = words.length;
I'm not sure what trouble you're having with methods but I dont think you need more than one, try this: it uses split to split up the words in a string, and you can chose the delimeters
String sentence = "This is a sentence.";
String[] words = sentence.split(" ");
for (String word : words) {
System.out.println(word);
}
then you can do:
numberOfWords = words.length();
if you want to use 3 methods, you can call a method from your main() method that does this for you, for example:
public String getInputString() {
Scanner in = new Scanner (System.in);
System.out.print("Enter a string: ");
String s = in.nextLine();
if (s.length() > 0) {
return s;
} else {
System.out.println("ERROR - string must not be empty.");
System.out.print("Enter a string: ");
return getInputString();
}
}
public int wordCount(String s) {
words = splitString(s)
return words.length();
}
public String[] splitString(String s) {
return s.split(" ");
}
Based on your code i think this is what you're trying to do:
private static int getWordCount(String input) {
int count = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ' ') {
count++;
}
}
return count;
}
Here's what I've done:
I've moved the code you were 'playing' with into the right method (getWordCount).
Corrected the loop you were trying to use (I think you have for and while loops confused)
Fixed your check for the space character (' ' not " ")
There is a bug in this code which you'll need to work out how to fix:
getWordCount("How are you"); will return 2 when it should be 3
getWordCount(""); will return 0
getWordCount("Hello"); will return 0 when it should be 1
Good luck!
Better use simple function of spilt() with arguments as space
int n= str.split(" ").length;
public static int Repeat_Words(String arg1,String arg2)
{
//It find number of words can be formed from a given string
if(arg1.length() < 1 || arg2.length() < 1)
return 0;
int no_words = 99999;
char[] str1 = arg1.toCharArray();
char[] str2 = arg2.toCharArray();
for(int x = 0; x < str1.length; x++)
{
int temp = 0;
for(int y = 0; y < str2.length; y++)
{
if(str1[x] == str2[y])
temp++;
}
if(temp == 0)
return 0;
if(no_words > temp)
no_words = temp;
temp = 0;
}
return no_words;
}
I'm trying to solve the string similarity question on interviewstreet.com. My code is working for 7/10 cases (and it is exceeding the time limit for the other 3).
Here's my code -
public class Solution {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String v1 = user_input.next();
int number_cases = Integer.parseInt(v1);
String[] cases = new String[number_cases];
for(int i=0;i<number_cases;i++)
cases[i] = user_input.next();
for(int k=0;k<number_cases;k++){
int similarity = solve(cases[k]);
System.out.println(similarity);
}
}
static int solve(String sample){
int len=sample.length();
int sim=0;
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
if(sample.charAt(j-i)==sample.charAt(j))
sim++;
else
break;
}
}
return sim;
}
}
Here's the question -
For two strings A and B, we define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings "abc" and "abd" is 2, while the similarity of strings "aaa" and "aaab" is 3.
Calculate the sum of similarities of a string S with each of it's suffixes.
Input:
The first line contains the number of test cases T. Each of the next T lines contains a string each.
Output:
Output T lines containing the answer for the corresponding test case.
Constraints:
1 <= T <= 10
The length of each string is at most 100000 and contains only lower case characters.
Sample Input:
2
ababaa
aa
Sample Output:
11
3
Explanation:
For the first case, the suffixes of the string are "ababaa", "babaa", "abaa", "baa", "aa" and "a". The similarities of each of these strings with the string "ababaa" are 6,0,3,0,1,1 respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11.
For the second case, the answer is 2 + 1 = 3.
How can I improve the running speed of the code. It becomes harder since the website does not provide a list of test cases it uses.
I used char[] instead of strings. It reduced the running time from 5.3 seconds to 4.7 seconds and for the test cases and it worked. Here's the code -
static int solve(String sample){
int len=sample.length();
char[] letters = sample.toCharArray();
int sim=0;
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
if(letters[j-i]==letters[j])
sim++;
else
break;
}
}
return sim;
}
used a different algorithm. run a loop for n times where n is equals to length the main string. for each loop generate all the suffix of the string starting for ith string and match it with the second string. when you find unmatched character break the loop add j's value to counter integer c.
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Solution {
public static void main(String args[]) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(in.readLine());
for (int i = 0; i < T; i++) {
String line = in.readLine();
System.out.println(count(line));
}
}
private static int count(String input) {
int c = 0, j;
char[] array = input.toCharArray();
int n = array.length;
for (int i = 0; i < n; i++) {
for (j = 0; j < n - i && i + j < n; j++)
if (array[i + j] != array[j])
break;
c+=j;
}
return c;
}
}
I spent some time to resolve this question, and here is an example of my code (it works for me, and pass thru all the test-cases):
static long stringSimilarity(String a) {
int len=a.length();
char[] letters = a.toCharArray();
char localChar = letters[0];
long sim=0;
int sameCharsRow = 0;
boolean isFirstTime = true;
for(int i=0;i<len;i++){
if (localChar == letters[i]) {
for(int j = i + sameCharsRow;j<len;j++){
if (isFirstTime && letters[j] == localChar) {
sameCharsRow++;
} else {
isFirstTime = false;
}
if(letters[j-i]==letters[j])
sim++;
else
break;
}
if (sameCharsRow > 0) {
sameCharsRow--;
sim += sameCharsRow;
}
isFirstTime = true;
}
}
return sim;
}
The point is that we need to speed up strings with the same content, and then we will have better performance with test cases 10 and 11.
Initialize sim with the length of the sample string and start the outer loop with 1 because we now in advance that the comparison of the sample string with itself will add its own length value to the result.
import java.util.Scanner;
public class StringSimilarity
{
public static void main(String args[])
{
Scanner user_input = new Scanner(System.in);
int count = Integer.parseInt(user_input.next());
char[] nextLine = user_input.next().toCharArray();
try
{
while(nextLine!= null )
{
int length = nextLine.length;
int suffixCount =length;
for(int i=1;i<length;i++)
{
int j =0;
int k=i;
for(;k<length && nextLine[k++] == nextLine[j++]; suffixCount++);
}
System.out.println(suffixCount);
if(--count < 0)
{
System.exit(0);
}
nextLine = user_input.next().toCharArray();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}