More Exercises

Longest Substring without repeating characters.

Example 1:

Input: abcabcdbb
Output: abcd

Example 2:

Input: aaaaa
Output: a

Solution:

public class Main {
    public static String longestNonRepeating(String str){
        String temp = "";
        String longest = "";

        for (int i = 0; i < str.length(); i++) {
            char current_char = str.charAt(i);

            //if in string
            //indexOf: Returns -1 if not found
            if (temp.indexOf(current_char) == -1){
                temp += current_char;
            } else { //if in string
                if (temp.length() > longest.length())
                    longest = temp;

                temp = ""; //Reset the string
            }
        }

        return longest.length()>temp.length() ? longest : temp; //Since it temp was always the longest
    }

    public static void main(String[] args) {
        String res = longestNonRepeating("pickoutthelongestsubstring");
        System.out.print("substring: " + res);
        System.out.println(", length: " +res.length());
    }
}

Tests

Length of each word

Given a string s containing a string seperated by spaces calculate the length of each word

Example 1:

Example 2:

Solution

Longest substring appears at both ends of a given string

Example 1:

Example 2:

Example 2:

Solution

tests

Last updated

Was this helpful?