I tried to count words with Streams in Java. Here's what I tried:
public static int countWords(String s) {
return s.chars().reduce((x, y) -> {
if((char)y == ' ')
++x;
return x;
}).orElse(0);
}
But countWords("asd") return 97. Why? I thought that chars returns IntStream which actually consists of chars. So, I just cast it to char. What's wrong?
While your question refers to counting words your code seems to be designed to count spaces. If that's your intention then I would suggest:
input.chars().filter(Character::isSpaceChar).count();
That avoids many of the casting complications you have in your code and you can change it to isWhitespace if that makes more sense for your domain.
If, however, you wish to count words then the simplest solution is to split on whitespace then count non-empty words:
Pattern.compile("\\s+").splitAsStream(input).filter(word -> !word.isEmpty()).count();
I would suggest more functional approach:
public static long countWords(String s) {
return Arrays
.stream(s.split(" "))
.filter(w -> !w.isEmpty())
.count();
}
There are different overloads of the reduce operator:
Optional reduce(BinaryOperator accumulator)
T reduce(T identity, BinaryOperator accumulator)
U reduce(U identity, BiFunction accumulator, BinaryOperator combiner)
If you don't specify the identity value for 'x', the reduce operator takes the first value from the stream. So 'x' ends up being the letter 'a', as an integer, which is 97. You probably want to change your code to this:
public static int countWords(String s) {
return s.chars().reduce(0, (x, y) -> {
if((char)y == ' ')
return x + 1;
return x;
});
}
While using reduce, you're working with tuples : x being the first char or an accumulator and y the secone char variable.
Here, x always points to a which ASCII value is 97
Pattern#splitAsStream(CharSequence)
You may want to use this method in your case, it does the job just right and you write an easier to maintain code.
public static int countWords(String s) {
return (int)Pattern.compile(" ")
.splitAsStream(s)
.count();
}
Counting spaces: see sprinter's response; performance: see comments to erkfel's response; correct application of reduce: see Andrew Williamson's response.
Now I combined them all to the following:
public static int countWords(String s)
{
int c = s.chars().reduce(0, (x, y) ->
{
if(x < 0)
{
if(Character.isWhitespace(y))
{
x = -x;
}
}
else
{
if(!Character.isWhitespace(y))
{
x = -(x + 1);
}
}
return x;
});
return c < 0 ? -c : c;
}
This counts real words, not the whitespace, in a very efficient way. There is a little trick hid within: I am using negative values to represent the state "within a word" and positive values to represent "within whitespace sequence". I chose this for not having to carry an additional boolean value, saving us from writing an explicit class implementing IntBinaryOperation (additionally, this keeps the lamda expression stateless, still parallelising as talked of in the reduction article would not be possible as this operator is not associative...)).
Edit: As Holger pointed out (I think rightly), this usage is abuse of how recude actually is intended (have several alike values and reduce them to a single one still alike the original ones; example: summating or multiplying a list of numerical values, result still is numerical - or concatenating a list of strings, result still is a string).
So simply iterating over the string seems to be more appropriate:
public static int countWords(String s)
{
int count = 0;
boolean isWord = false;
for(int i = 0; i < s.length(); i++)
{
if(isWord)
{
if(Character.isWhitespace(s.charAt(i)))
{
isWord = false;
}
}
else
{
if(!Character.isWhitespace(s.charAt(i)))
{
++count;
isWord = true;
}
}
return count;
}
I personally like compact variants, although less understandable:
public static int countWords(String s)
{
int count = 0;
boolean isWord = false;
for(int i = 0; i < s.length(); i++)
{
boolean isChange = isWord == Character.isWhitespace(s.charAt(i));
isWord ^= isChange;
count += isWord & isChange ? 1 : 0;
}
return count;
}
Streams? How about:
int wordCount = str.trim().split("\\s+").length();
If you desperately must use streams (not recommended):
int wordCount = Arrays.stream(str.trim().split("\\s+")).count();
Related
I have tried out 387.First Unique Character In A string
Given a string s, find the first non-repeating character in it and
return its index. If it does not exist, return -1.
EXAMPLE : 1
Input: s = "leetcode"
Output: 0
EXAMPLE :2
Input: s = "loveleetcode"
Output: 2
I have been trying this problem. I thought we will pick one by one all the characters and check if a repeating character exists break from the loop. And if not then return that index.I have thought over a solution which I believe is not the most efficient way but I want to know the how can I solve this problem with the approach given below:
public int firstUniqChar(String s) {
for(int i=0;i<s.length();i++){
for(int j=i+1;j<s.length();j++){
if(s.charAt(i)==s.charAt(j)){
break;
}
}
}
return -1;
}
I'm confused how to return the index.I'm unable to find the logic after:
for(int j=i+1;j<s.length();j++){
if(s.charAt(i)==s.charAt(j)){
break;
}
}
If anyone can help me find out the logic here.
Try this.
public static int firstUniqChar(String s) {
L: for (int i = 0, length = s.length(); i < length; i++) {
for (int j = 0; j < length; j++)
if (i != j && s.charAt(i) == s.charAt(j))
continue L;
return i;
}
return -1;
}
public static void main(String[] args) {
System.out.println(firstUniqChar("leetcode"));
System.out.println(firstUniqChar("loveleetcode"));
System.out.println(firstUniqChar("aabb"));
}
output:
0
2
-1
you can use a flag variable.
public int firstUniqChar(String s) {
int flag=0;
for(int i=0;i<s.length();i++){
flag=0;
for(int j=0;j<s.length();j++){
if(s.charAt(i)==s.charAt(j) && i!=j){
flag=1;
break;
}
}
if(flag==0){
return i;
}
}
return -1;
}
There are 26 possible lowercase English letters, so you could use two 26 element arrays.
One array, letterCount, keeps counts of each letter. Start at 0 and add 1 every time the corresponding letter appears in the text string. The second array, position, holds the position of the first occurrence of that letter, or -1 if the letter never appears. You will need to initialise that array to -1 for all elements.
Process the string in order, recording initial positions, once only for each letter, and incrementing the count for each letter in the string.
After the string has been processed, look through the letterCount array. If there are no letters with a 1 count then return -1. If exactly one letter has a 1 count, then return the position of that letter from the position array. If more than one letter has a 1 count, then pick the one with the lowest value for its position.
Using two loops is a highly inefficient way of solving this problem. The string can be up to 100,000 characters long and you are processing it multiple times. Far better to process it only once, keeping track of what you have found so far.
Fix you code
You need to add a variable that tells you if you have breaked the loop or not
static int firstUniqChar(String s) {
boolean duplicate;
for (int i = 0; i < s.length(); i++) {
duplicate = false;
for (int j = i + 1; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
duplicate = true;
break;
}
}
if (!duplicate) {
return i;
}
}
return -1;
}
Improve
There is a smarter way, that is finding the last index occurence of the current char, if it's equal to the current index : that char is unique and you return its index
static int firstUniqChar(String s) {
for (int i = 0; i < s.length(); i++) {
if (s.lastIndexOf(s.charAt(i)) == i) {
return i;
}
}
return -1;
}
If you do not bother about time complexity using IdenxOF operations, then one can try this solution.
indexOf() – also runs in linear time. It iterates through the internal array and checking each element one by one. So the time
complexity for this operation always requires O(n) time.
int firstUniqCharOneLoop(String str) {
for (int i = 0; i < str.length(); i++) {
if (str.indexOf(str.charAt(i))== str.lastIndexOf(str.charAt(i)) ) {
return i;
}
}
return -1;
}
The lowest complexity I managed to achieve:
public class UniqueSymbolFinder {
static int findFirstUniqueChar(String s) {
Set<Character> set = new HashSet<>(s.length());
List<CharWithIndex> candidates = new LinkedList<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
CharWithIndex charWithIndex = new CharWithIndex(ch, i);
if (set.add(ch)) {
candidates.add(charWithIndex);
} else {
candidates.remove(charWithIndex);
}
}
return candidates.size() == 0 ? -1 : candidates.get(0).index;
}
/**
* Class for storing the index.
* Used to avoid of using an indexOf or other iterations.
*/
private static class CharWithIndex {
int index;
char ch;
private CharWithIndex(char ch, int index) {
this.ch = ch;
this.index = index;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CharWithIndex that = (CharWithIndex) o;
return ch == that.ch;
}
#Override
public int hashCode() {
return Objects.hash(ch);
}
}
}
I believe the memory usage can still be optimized.
100% Correct JAVA Solution
Since the question is about returning the index of the first non-repeating character in a string, we need some data structure to save the index of each character in the string for us.
I choose here the HashMap of Java. Basically, what you can do with it, you can save a pair of values (or pair of other data structures).
So, in my solution, I am saving a Character Integer pair. The first is considered as a key (here it is each character in the string), and the second is its index value.
The problem here is that we only want to keep the minimum index of non-repeating characters and that's why if you take a look below, you will find the maxIndexForRepeatedValues is set to be 10 power 5 as the input constraint says 1 <= s.length <= 10 power 5.
However, I am using that value to neglect repeated characters that would be found in the HashMap and at the end, we retrieve the minimum index which is the index of course for the first character from the map, or if there were only repeated characters, we return -1.
To make the code shorter, I used ternary-operator but you can write it with if-else if you want!
class Solution {
public int firstUniqChar(String s) {
int maxIndexForRepeatedValues = 100000;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0 ; i < s.length() ; i++) {
char key = s.charAt(i);
int resIndex = map.containsKey(key) ? maxIndexForRepeatedValues : i;
map.put(key, resIndex);
}
int minIndex = Collections.min(map.values());
return minIndex == maxIndexForRepeatedValues ? -1 : minIndex;
}
}
I have to implement the .length method from String class "by hand" and I have no idea and hope you can help somehow.
No other methods or functions are allowed, than:
String.charAt()
String.substring()
String.isEmpty()
Bit-operations &,|, &&,||, <<, >>,>>>, !=, ==
Arithmetic operations
for and while Loop
recursion
if else statement
self created methods (int,String,char,boolean etc.)
self-created Arrays. (no Methods of them)
static void manual_length2(String length) {
//example String length = "Hello" = 5 letters.
int counter = 0;
int i = 0;
char g = ' ';
while(i <= 4 ) { /*4 is the number i already know */
g = length.charAt(i);
counter += 1;
length.substring(1);
++i;
}
System.out.println(counter);
Console: 5
This was my approach, but I'm stuck in the while statement's condition to terminate.
With the example "Hello" i already know that this word has 5 letters, but it needs to fit for all inputs. So i don't know how to express to border-value of the while statement.
Another approach is by recursion, but also, i ask myself how can i express the limit of the recursion.
How can i express:
.... lengthMethod1(String length, int ???) {
if(n == 0) {
return length.charAt(0);
}
else {
return ???? lengthMethod1(length, n - 1);
}
You can loop until the String is empty while removing the first character on each iteration.
static int manual_length(String str) {
int len = 0;
while(!str.isEmpty()){
++len;
str = str.substring(1);
}
return len;
}
This can be converted to a tail-recursive method as well.
static int manual_length(String str) {
return str.isEmpty() ? 0 : 1 + manual_length(str.substring(1));
}
Another approach is by recursion, but also, i ask myself how can i
express the limit of the recursion. How can i express:
Yes, you can do recursively like this:
static int manual_length(String str, int len) {
return str.isEmpty() ? len : manual_length(str.substring(1), len + 1);
}
You use an accumulator variable (i.e., len), that you increment, while removing a char from the string (i.e., str.substring(1)). When you reach the end (i.e., str.isEmpty()) you return the accumulator.
I need to write an answer with the least complexity degree. My questions is regarding nested-loops that do not always run. I have a for loops that iterates N times, depending on length of the string, and searches for a 'char' value. When it finds it, it iterates the loop again from this point onwards, looking for more 'char' values.
I wrote the following method:
public static int subStrMaxC(String s, char c, int k) {
char[] stringChars=new char[s.length()];
//System.out.print("the string of the characters is");
for(int i=0;i<stringChars.length;i++) {
stringChars[i]=s.charAt(i);
// System.out.print(stringChars[i]);
}
int count=0;
int bigcount=0;
int[] charArray=new int[s.length()];
for(int i=0;i<stringChars.length;i++) {
count=0;
if(stringChars[i]=='c') {
count++;
for(int j=i+1;j<stringChars.length;j++) {
if(stringChars[j]=='c') {
count++;
if((count>=2)&&(count<=k+2)) {
bigcount++;
if(count==k+2) {
count=0;
j=stringChars.length-1;
}
}
}
}
}
}
return bigcount;
}
Since the second loop do not iterate unless the first loop finds a value that meets the condition, I did not know whether the complexity is defined O(n^2)-which is my assumption, as the second loop can, in the worst case run N*(N-i) times- or just O(n), which is what I'm looking for.
Thank you!
I am quite sure this is the best you can do, but of course I may be wrong. The problem you have with your approach is your limited use of Space Complexity. With the approach below, you iterate through the string only once (i.e. no 'j' loop which leads to the n squared problem). Here you build out candidate substrings by using space/memory. Now you only have to iterate over candidate substrings which has a much lower time complexity than your first approach.
public class MaxKSubstring {
public static void main(String[] args) {
String INPUT = "testingwithtees";
char C = 't';
int K = 1;
int count = subStrMaxC(INPUT, C, K);
System.out.println(count);
}
public static int subStrMaxC(String s, char c, int k) {
char letters[] = s.toCharArray();
int valid = 0;
List<Candidate> candidates = new ArrayList<Candidate>();
for (int i=0; i< s.length(); i++) {
if (letters[i] == c)
candidates.add(new Candidate(k, c));
for (Candidate candidate : candidates) {
if (candidate.addLetter(letters[i])) {
System.out.println(candidate.value);
valid++;
}
}
}
return valid;
}
}
class Candidate {
final int K;
final char C;
public Candidate(int k, char c) {
super();
K = k;
C = c;
}
boolean endsWithC = false;
String value = "";
int kValue = 0;
public boolean addLetter(char letter) {
endsWithC = false;
value = value+letter;
if (letter == C) {
kValue++;
endsWithC = true;
}
return endsWithC && kValue <= K+2 && value.length() > 1;
}
}
O(n) best case,
O(n2) worst case
I'm not sure what you mean by the least complexity. If you are referring to the best case, that would be O(n) performance. (The parent loop iterates only and the nested loops are never iterated) since the matching case:
if(stringChars[i]=='c')
Is always false. However, the worst case time complexity which is usually what we're referring to is O(n2), owing to the fact that the condition if(stringChars[i]=='c') returns true every single time.
I'm making a small program that determines the minimum integer of 3 integers. I'm having problems returning the integers back into the variable answer.
Here Is how I imagine the program working;
PROGRAM RUNS:
Looks for Method called "Minimumum" with the listed argument.
Determines the minimum integer and returns it back to the method Minimum
This value gets stored in the answer variable
Code:
public class Method {
public static void main(String[] args) {
int answer = Minimum(20, 40, 50);
}
public static int Minimum(int first, int second, int third) {
if ((first < (second) && (first < third))) {
return first;
} else if ((second < (first) && (second < third))) {
return second;
} else if (((third < first) && (third < second))) {
return (third);
} else {
System.out.println("error");
}
}
}
You need to return a result in all cases, so your else block is incorrect. Do you really think there is a fourth case ? No, there isn't : there are three integers so the minimum is one of those three, meaning there only are 3 cases... Simply remove the else block. By the way, why do you use so many parentheses ? It's useless, and unreadable.
public static int Minimum(int first, int second, int third){
if (first < second && first < third)
return first;
else if (second < first && second < third)
return second;
else
return third;
}
As noted by the others, this is not sufficient to make your method correct. Indeed, you don't care about strict inequality here because when two numbers are the same, you can choose either of them as the minimum. This code breaks if the two first parameters are equal. To fix it, simply use <= instead of < (everywhere).
Your code looks a bit complicated.
int Minimum(int first, int second, int third) {
int min = first;
if (second < min) {
min = second;
}
if (third < min) {
min = third;
}
return min;
}
This looks creepy, but it should do it.
Hope it helps to understand.
You have to return in your final else block. But you could simplify your code with Math.min(int, int). Something like,
public static int Minimum(int first, int second, int third) {
return Math.min(first, Math.min(second, third));
}
Minimum function should always return the integer value in any case. After else, add return statement.
In Java 8+ your method could also look as follows:
public static int minimum(Integer val1, Integer val2, Integer val3){
List<Integer> list = Arrays.asList(new Integer[]{val1, val2, val3});
return list.stream().min((Integer v1, Integer v2) -> v1 < v2 ? 0 : 1 ).get();
}
I have to solve an exercise, counting all the uppercase chars in a String - recursively - Anyhow I thought I might have found a solution - but it won't work…
Probably you might help me? Thanks!
public static int CountCapitals(String s) {
int counter = 0;
// if (Character.isUpperCase(s.charAt(0)))counter+=1;
if (s.length() == 0)
return counter;
if (s.length() == 1 && s.charAt(0) < 65 && s.charAt(0) > 90)
return 0;
if (s.charAt(0) < 'A' && s.charAt(0) > 'Z') {
return CountCapitals(s.substring(1));
}
if (s.charAt(0) >= 'A' && s.charAt(0) <= 'Z')
counter++;
return CountCapitals(s.substring(1));
}
The problem with your code is the use of counter: each level of invocation has its own counter, initially set to zero. The ++ operator at the bottom has no effect.
You need to compute the result of this invocation based on the result of the previous invocation. Your base case (i.e. s.length() == 0) is fine; the rest of your code needs to change so that it returns whatever CountCapitals(s.substring(1)) when the first letter is non-capital; when the first letter is capital, your function should return 1 + CountCapitals(s.substring(1)).
You need to consider the case when the length of string is 1 and the only character is uppercase (in this case, you should return 1).
Also you need to pass in the counter as a parameter rather than expecting it to "carry over" into other function calls.
This recursion should do just what you want:
public static int countCapitals(String s) {
if (s.length() == 0) return 0;
int cap = Character.isUpperCase(s.charAt(0)) ? 1 : 0;
return countCapitals(s.substring(1)) + cap;
}
If this wasn't a home assignment, you could try an iterative approach which is about 5-10 times faster:
public static int countCapitals(String s) {
int count = 0;
for (int idx = 0; idx < s.length(); idx++) {
if (Character.isUpperCase(s.charAt(idx))) {
count++;
}
}
return count;
}
You don't really need to use a counter variable to keep track of the number of capitals. Instead, you can just the recursive calls, themselves, to keep track of the total:
public static int CountCapitals(String s)
{
if (s.length() == 1)
return (Character.isUpperCase(s.charAt(0)) ? 1 : 0);
else
return CountCapitals(s.substring(1)) +
(Character.isUpperCase(s.charAt(0)) ? 1 : 0);
}
If this is for an assignment and you have to use ASCII values, then fine, but if not, you really should just Character.isUpperCase(char c). In case you're not familiar with the conditional operator, it's defined as follows:
if(someExpression == true)
{
//output 1
}
else
{
//output 0
}
is represented succinctly as:
(someExpression == true) ? 1 : 0
NB:
In your example, counter is set to 0 at the beginning of each method call, so that's why it's not working. If you really want to use a counter, pass it as a parameter to the method instead, and update the parameter with each method call. When you get to the end of the String, simply return the parameter.
You try this
public class HelloWorld{
public static int isUpperCase(String str){
if(str.length()==0) return 0;
boolean check =Character.isUpperCase(str.charAt(0));
if(check){
return isUpperCase(str.substring(1))+1;
}
return isUpperCase(str.substring(1));
}
public static void main(String []args){
String n= "FSAsdsadASdcCa";
System.out.println(isUpperCase("FSAsdsadASdcCa"));
}
}