iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 27
1
自我挑戰組

見習村-30 Day CodeWars Challenge系列 第 27

見習村27 - First non-repeating character

  • 分享至 

  • xImage
  •  

27 - First non-repeating character

Don't say so much, just coding...

Instruction

Write a function named first_non_repeating_letter that takes a string input, and returns the first character that is not repeated anywhere in the string.

For example, if given the input 'stress', the function should return 't', since the letter t only occurs once in the string, and occurs first in the string.

As an added challenge, upper- and lowercase letters are considered the same character, but the function should return the correct case for the initial letter. For example, the input 'sTreSS' should return 'T'.

If a string contains all repeating characters, it should return an empty string ("") or None -- see sample tests.

Ruby

Init

  def tongues(code)
    #your code here
  end

Sample Testing

 Test.describe('Simple Tests') do
    it('should handle simple tests') do
      Test.assert_equals(first_non_repeating_letter('a'), 'a')
      Test.assert_equals(first_non_repeating_letter('stress'), 't')
      Test.assert_equals(first_non_repeating_letter('moonmen'), 'e')
    end
    it('should handle empty strings') do
      Test.assert_equals(first_non_repeating_letter(''), '')
    end
  end

Javascript

Init

  function firstNonRepeatingLetter(s) {
    // Add your code here
  }

Sample Testing

  Test.describe('Simple Tests', function() {
    it('should handle simple tests', function() {
      Test.assertEquals(firstNonRepeatingLetter('a'), 'a');
      Test.assertEquals(firstNonRepeatingLetter('stress'), 't');
      Test.assertEquals(firstNonRepeatingLetter('moonmen'), 'e');
    });
  });

Thinking

https://ithelp.ithome.com.tw/upload/images/20201012/20120826YzLdi5jaAH.jpg
圖片來源:Unsplash Nikita Kachanovsky

Hint & Reference

Solution

Ruby

  # Solution 1
  def first_non_repeating_letter(s)
    letter = s.chars.find{ |char| s.chars.map(&:downcase).count(char.downcase) == 1 }
    letter.nil? ? '' : letter
  end
  
  # Solution 2
  def first_non_repeating_letter(s)
    s.chars.find{ |i| s.downcase.count(i) == 1 || s.upcase.count(i) == 1 } || ''
  end

Javascript

  // Solution 1
  function firstNonRepeatingLetter(s) {
    for(var i in s) {
      if(s.match(new RegExp(s[i],"gi")).length === 1) {
        return s[i];
      }
    }
    return '';
  }

上一篇
見習村26 - Tongues
下一篇
見習村28 - Find the missing letter
系列文
見習村-30 Day CodeWars Challenge30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言