0
Help us understand the problem. What are the problem?

posted at

【LeetCode】3. Longest Substring Without Repeating Charactersを解いてみた

はじめに

コーディングテスト対策としてLeetCodeの3. Longest Substring Without Repeating Charactersを解いていく。

問題文を和訳

  • 文字列sが与えられた場合、
  • 文字を繰り返さずに最長の部分文字列の長さを見つけます。
  • Input: s = "abcabcbb"
  • Output: 3
    Explanation: The answer is "abc", with the length of 3.

回答

3_LongestSubstringWithoutRepeatingCharacters.rb
def length_of_longest_substring(s)
  longest = 0
  left = 0
  right = 0
  str = []
  while right < s.length
    if str.include?(s[right])
      left = str.index(s[right]) + 1
      str = str[left..-1]
      str.push(s[right])
    else
      str.push(s[right])
      if str.length > longest
        longest = str.length
      end
    end
    right += 1
  end
  return longest
end

最後に

難易度はEasyでした。

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
0
Help us understand the problem. What are the problem?