Home > OS >  How to obtain the length of the last word in the string
How to obtain the length of the last word in the string

Time:03-07

I have reversed the string and have a for loop to iterate through the reversed string.

I am counting characters and I know I have a logic flaw, but I cannot pinpoint why I am having this issue.

The solution needs to return the length of the last word in the string.

My first thought was to iterate through the string backward (I don't know why I decided to create a new string, I should have just iterated through it by decrementing my for loop from the end of the string).

But the logic should be the same from that point for my second for loop.

My logic is basically to try to count characters that aren't whitespace in the last word, and then when the count variable has a value, as well as the next whitespace after the count has counted the characters of the last word.

class Solution {
    public int lengthOfLastWord(String s) {
        int count = 0;
        int countWhite = 0;
        char ch;
        String reversed = "";
        for(int i = 0; i < s.length(); i  ) {
            ch = s.charAt(i);
            reversed  = ch;
        }
        
        for(int i = 0; i < reversed.length(); i  ) {
            if(!Character.isWhitespace(reversed.charAt(i))) {
                count  ;
                if(count > 1 && Character.isWhitespace(reversed.charAt(i)) == true) {
                    break;
                }
            }
        }
        return count;
        
    }
}

CodePudding user response:

Maybe try this,

public int lengthOfLastWord(String s) {
    
String [] arr = s.trim().split(" ");


return arr[arr.length-1].length();

}

CodePudding user response:

Firstly, as you have mentioned, your reverse string formed is just a copy of your original string. To rectify that,

for (int i = s.length() - 1; i >= 0; i--) {
            ch = s.charAt(i);
            reversed  = ch;
        }

Secondly, the second if condition is inside your first if condition. That is why, it will never break ( because you are first checking if character is whitespace, if it is, then you are not going inside the if statement, thus your second condition of your inner if loop will never be satisfied).

public class HW5 {
    public static void main(String[] args) {

        String s = "My name is Mathew";
        int count = lengthOfLastWord(s);
        System.out.println(count);

    }

    public static int lengthOfLastWord(String s) {
        int count = 0;
        int countWhite = 0;
        char ch;
        String reversed = "";
        System.out.println("original string is----"   s);
        for (int i = s.length() - 1; i >= 0; i--) {
            ch = s.charAt(i);
            reversed  = ch;
        }
        System.out.println("reversed string is----"   reversed);
        for (int i = 0; i < reversed.length(); i  ) {
            if (!Character.isWhitespace(reversed.charAt(i)))
                count  ;
            if (count > 1 && Character.isWhitespace(reversed.charAt(i)) == true) {
                break;
            }

        }
        return count;

    }
}

=

 and the output is :
    original string is----My name is Mathew
    reversed string is----wehtaM si eman yM
    6

Another way to go about is : you use the inbuilt function split which returns an array of string and then return the count of last string in the array.

CodePudding user response:

Another option would be to use index of last space and calculate length from it:

public int lengthOfLastWord(String string) {
    int whiteSpaceIndex = string.lastIndexOf(" ");
    if (whiteSpaceIndex == -1) {
        return string.length();
    }
    int lastIndex = string.length() - 1;
    return lastIndex - whiteSpaceIndex;
}

String.lastIndexOf() finds the start index of the last occurence of the specified string. -1 means the string was not found, in which case we have a single word and length of the entire string is what we need. Otherwise means we have index of the last space and we can calculate last word length using lastIndexInWord - lastSpaceIndex.

CodePudding user response:

There are lots of ways to achieve that. The most efficient approach is to determine the index of the last white space followed by a letter. It could be done by iterating over indexes of the given string or simply by invoking method lastIndexOf().

Keeping in mind that the length of a string that could be encountered at runtime is limited to Integer.MAX_VALUE, it'll not be a performance-wise solution to allocate in memory an array, produced as a result of splitting of this lengthy string, when only a length of a single element is required.

The code below demonstrates how to address this problem with Stream IPA and a usual for loop.

The logic of the stream:

  • Create an IntStream that iterate over the indexes of the given string starting from the last.
  • Discard all non-alphabetic symbol at the end of the string with dropWhile().
  • Than retain all letters until the first non-alphabetic symbol encountered by using takeWhile().
  • Get the count of element in the stream.

Stream-based solution:

public static int getLastWordLength(String source) {
    return (int) IntStream.iterate(source.length() - 1, i -> i >= 0, i -> --i)
            .map(source::charAt)
            .dropWhile(ch -> !Character.isLetter(ch))
            .takeWhile(Character::isLetter)
            .count();
}

If your choice is a loop there's no need to reverse the string. You can start iteration from the last index, determine the values of the end and start and return the difference.

Just in case, if you need to reverse a string that is the most simple and efficient way:

new StringBuilder(source).reverse().toString();

Iterative solution:

public static int getLastWordLength(String source) {
    int end = -1; // initialized with illegal index
    int start = 0;
    for (int i = source.length() - 1; i >= 0; i--) {
        if (Character.isLetter(source.charAt(i)) && end == -1) {
            end = i;
        }
        if (Character.isWhitespace(source.charAt(i)) && end != -1) {
            start = i;
            break;
        }
    }
    return end == -1 ? 0 : end - start;
}

main()

public static void main(String[] args) {
    System.out.println(getLastWord("Humpty Dumpty sat on a wall  % _ (&)"));
}

output

4   -   last word is "wall
  • Related