见习村27 - First non-repeating character

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 '';
  }

<<:  python30天-DAY28-Matplotlib(子图)

>>:  乔叔教 Elastic - 27 - Elasticsearch 的优化技巧 (1/4) - Indexing 索引效能优化

D4 第二周 (回忆篇)

今天会是比较划水的回忆篇,可以斟酌看看。 这周开始正式学习 javascript,然後那时候疫情还没...

Day 10 - Design System x 实作 — Icon 元件

今天就要来实作 Icon 啦!事不宜迟直接开始! 想先看 Code 或是 Demo 的由此去: G...

Day22 又回到最初的起点 呆呆地看着萤幕前

Bootstrap table 就在我们寻寻觅觅如何让表格的功能更完整的时候,我们看到了一道光,这...

26/一起成为国际研讨会讲师!!!(投稿篇)

CFP是Call for Papers/Call for Proposals的缩写,中文可以称作是研...

VMware guest搬迁後,windows server VPN功能失效

大家好, 本人有台Windows Server 2008 R2 Standard一直於Vmware ...