Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Basically, I am getting ready for an interview and following a regime that gives me a bunch of challenges that are often thrown in interviews.
This particular challenge's goal is to count the number of words that appear more than once in a sentence excluding punctuations. I did it but it took me at least 5 minutes to come up with it and code it.
I'm not sure if taking 5 minutes is acceptable to code something like this in java interviews so I would like to see something simpler with maybe less code. Below is how I solved it.
System.out.println("Part 6 challenge-------------------------------------------------------------------------");
String sentence3 = "She's the queen and likes, apples APPLES, bananas BANANAS Bananas, and oranges ORANGE."; //original string
StringBuilder sb3 = new StringBuilder(); //declared string builder to build new string without punctuations
char [] punctuations = {'.',',',':','?','!',';'};//Char array containing punctuations to lookout for
for (int i=0; i<sentence3.length(); i++){
boolean p = false; //declared boolean within loop to turn on if punctuation was found in the original string
for (Character c: punctuations){
if (sentence3.charAt(i) == c){
p = true;// turn on
}
} if(!p){
sb3.append(sentence3.charAt(i));//if no punctuations found, add it to the string builder to build new string
}
}
String word[] = sb3.toString().split(" ");
Set<String> uniqueWords = new HashSet<>();
int count = 0;
for (String s: word) {
uniqueWords.add(s.toLowerCase());
}
for (String s: uniqueWords){
for (String w: word){
if (s.equals(w.toLowerCase())){
count++;
}
}
System.out.println(String.format("Found %s %d times", s, count));
count =0;
}
A shorter way, outlined:
Split by regexp;
Filter for words (may be not needed depending on your regexp);
Replace Set<String> with a Map<String, Integer> and count word quantities in linear time;
Filter out and output words with count > 1.
BTW this can all be one stream expression if you're into minimal statement count.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
We will be given a string s. Suppose for example "creepfe". What we want to do is to remove duplicate and instead add a new letter in that place and new letter must be distinct letter available next to the duplicate letter in alphabetical order. So it goes like this :
creepfe to crefpfe -- first e is distinct and second e is changed to f which is distinct upto that.
crefpfe to crefpge -- second f is changed to g since we already have f before.
crefpge to crefpgf -- since e is already present.
Now again we got f duplicate , so change it to crefpgg , which again got g duplicate so finally we reach "crefpgh" which has all distinct letters.
Started learning java recently and a working code is appreciated ,BUT a good algorithm is what really needed.
Edit : yes capitals do count as duplicates as well. And string length is limited to 10-15 so no worry about running out of distinct letter.
Here's a solution. I m using recursion to left shift the letters if there are duplicates. I also went back and redid my code to include sets as mentioned by MBo. Its not the most efficient, but its a start while you wait for advice from more experienced members of SO
public class tester {
public static void main(String[] args){
//Application.launch(testclass.class, args);
String str = "creepFeZZ";
System.out.println(processStr(str));
}
public static String processStr(String str){
StringBuilder sb = new StringBuilder();
HashSet<String> seen = new HashSet<>();
insertStr(sb, seen, String.valueOf(str.charAt(0)));
for (int i=1; i<str.length(); i++){
char currentchar = str.charAt(i);
char processedchar = goNext(seen, currentchar);
insertStr(sb, seen, String.valueOf(processedchar));
}
//System.out.println(seen.toString());
return sb.toString();
}
private static void insertStr(StringBuilder sb, HashSet seen, String str){
seen.add(str.toLowerCase());
sb.append(str);
}
private static char goNext(HashSet seen, char c){
if (c>= 65 && c<=90){
//if uppercase letter, check if contains lowercase version
if (seen.contains(String.valueOf((char)(c+32)))){
c = goNext(seen, (char)(c+1));
}
//any left shifting will overflow back to A
return (char) ((c -(int) 'A') % 26 +(int) 'A');
}else{
//if lowercase letter, just check if contains
if (seen.contains(String.valueOf((char)(c)))){
c = goNext(seen, (char)(c+1));
}
//any left shifting will overflow back to a
return (char)((c-(int) 'a') % 26 +(int) 'a');
}
}
}
This gives output of:
crefpGhZA
Find the position where the string contains a duplicate. There are various methods to this. You can Google to find the most efficient one that fits your approach.
Generate the next character in alphabetical order. The following code shows how this can be done
String value = "C";
int charValue = value.charAt(0);
String next = String.valueOf( (char) (charValue + 1));
System.out.println(next);
Repeat the process until there are no more duplicates (have a while loop which breaks when there are no more duplicates)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
How can I find the average word length from the String text argument? I have void someMethod(String text){}. The word consists of letters and numbers. It is necessary to take into account gaps and punctuation marks
public static List<String> someMethod(String text) {
String[] words = text.split("\\p{P}?[ \\t\\n\\r]+"); // split by whitespace
int count = 0;
double sum = 0;
for (String word : words) {
double wordLength = word.length();
sum += wordLength;
count++;
}
final double average = sum / count;
List<String> list = Arrays.stream(words).filter(s -> s.length()>= average).collect(Collectors.toList());
list.sort(Comparator.comparingInt(s -> Math.abs(s.length() - "intelligent".length())));
return list;
}
Split string to words using split() method (it is overloaded, I think I would choose one with regexp as parameter) and then iterate over the array(which split () will return) and call length () for each element.
P.S. Before asking, please firstly do these things:
Try, Search, Read documentation
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to split a String at every Nth occurence, but missing the last values.Here is what is expected.
Input : String str = "234-236-456-567-678-675-453-564";
Output :
234-236-456
567-678-675
453-564
Here N=3, where the str should be split at every 3rd occurence of -.
Try this.
String str = "234-236-456-567-678-675-453-564";
String[] f = str.split("(?<=\\G.*-.*-.*)-");
System.out.println(Arrays.toString(f));
result:
[234-236-456, 567-678-675, 453-564]
You can try the following with Java 8:
String str = "234-236-456-567-678-675-453-564";
Lists.partition(Lists.newArrayList(str.split("-")), 3)
.stream().map(strings -> strings.stream().collect(Collectors.joining("-")))
.forEach(System.out::println);
Output:
234-236-456
567-678-675
453-564
Maybe one of the worst way without using function available in java , but good like exercise :
public static void main(String[] args){
String s = "234-236-456-567-678-675-453-564";
int nth =0;
int cont =0;
int i=0;
for(;i<s.length();i++){
if(s.charAt(i)=='-')
nth++;
if(nth == 3 || i==s.length()-1){
if(i==s.length()-1) //with this if you preveent to cut the last number
System.out.println(s.substring(cont,i+1));
else
System.out.println(s.substring(cont,i));
nth=0;
cont =i+1;
}
}
}
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 8 years ago.
Improve this question
{
public static int WordCount (String cString)
{
String currentWord;
int index;
int spacePos;
int validWordCount=0;
boolean validWord;
char upClowC;
cString=cString.trim()+" ";
spacePos=cString.indexOf(" ");
validWord=true;
for(index=0;index<cString.length();index++)
{
currentWord=cString.substring(0,spacePos);
upClowC=Character.toUpperCase(currentWord.charAt(index));
if(upClowC<'A'||upClowC>'Z')
{
validWord=false;
}
}
if(validWord==true)
{
validWordCount++;
}
return validWordCount;
}
public static void main(String[] args)
{
String sentence;
System.out.println("enter a sentence:");
sentence=EasyIn.getString();
WordCount(sentence);
}
}
I'm trying to create a method which takes a sentence and picks out the valid words (i.e. no numbers or symbols), but I keep getting an out of bounds error.
I can't use an array.
Your problem is here:
currentWord = cString.substring(0, spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
currentWord gets shorter, but index is still running from 0 to the length of the string.
General notes:
Follow Java naming conventions and change the name of your method to begin with small letter
if(validWord) is enough when you want to compare something to true, otherwise it's like asking "is it true that the value is true" instead of simply "is the value true"
Next time post your stack trace to get better and sooner help
In your code, you are doing
spacePos = cString.indexOf(" ");
And then inside the loop:
currentWord = cString.substring(0,spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
Now, because of the loop, the index will take values from 0 to your string length minus 1. If your substring (currentWord) is smaller than your string - which probably is -, then currentWord.charAt(index) will try to index out of the bounds of the substring, which is why you get the error.
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 8 years ago.
Improve this question
I want to store all possible substring in String []. I tried this but got an error:
public void sub(String word){
String [] Str=new String[100];
int n=0;
for (int from = 0; from < word.length(); from++) {
for (int to = from + 1; to <= word.length(); to++) {
str[n]=word.substring(from, to);
n++;
System.out.println(str[n]);
}
}
}
What is solution?
error is: cannot find symbol, variable str, loction: class substring
Well, that fairly clearly tells you what the error is: You haven't declared str. You have declared Str, but Java's identifiers are case sensitive, str and Str are not the same identifier.
So change
String [] Str=new String[100];
to
String [] str=new String[100];
// ^--- lower case
Before, when you hadn't said what the error was, there were a couple of other things Pshemo and I (amongst others) noticed:
You have a sequence issue here:
str[n]=word.substring(from, to);
n++;
System.out.println(str[n]);
...since you're incrementing n before outputting the string, you're always going to output null. Just moving the increment fixes that:
str[n]=word.substring(from, to);
System.out.println(str[n]);
n++;
Another possible problem can occur for longer words, where number of substrings can be more then 100. In that case you should avoid creating fixed size array, but try using dynamic size collection like List
List<String> str = new ArrayList<String>();
To put or read elements here just use str.add(substring) and str.get(index).