Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
中文翻譯
給予一個字串 s,找到第一個不重複的字元並回傳其索引,如果不存在則回傳 -1 。
範例及題目限制
解題思路
C# 解決方案
方案1 – Dictionary & HashSet
public class Solution {
public int FirstUniqChar(string s) {
Dictionary<char,int> dict = new Dictionary<char,int>();
HashSet<char> hSet = new HashSet<char>();
for(int i = 0; i<s.Length;i++)
{
char c = s[i];
if(hSet.Contains(c))
{
continue;
}
if (!dict.ContainsKey(c))
{
dict.Add(c, i);
}
else
{
dict.Remove(c);
hSet.Add(c);
}
}
if(dict.Count == 0)
{
return -1;
}
return dict.MinBy(k => k.Value).Value;
}
}
在第一個解法中,我們使用dictionary來儲存字元跟索引 ➡ 如果遇到第二次就會將其移除
HashSet 則用來記錄已經處理過的字元 ➡ 出現過兩次以上的 ➡ 以後遇到就跳過
時間複雜度 : O(n)
方案2 – ascii code 搭配 indexOf
public class Solution {
public int FirstUniqChar(string s) {
int min = Int32.MaxValue;
for (char c = 'a'; c <= 'z'; c++)
{
int tmp = s.IndexOf(c);
if(tmp!=-1 && tmp == s.LastIndexOf(c))
{
min = tmp<min ? tmp : min;
}
}
min = min == Int32.MaxValue ? -1 : min;
return min;
}
}
class Solution {
public int firstUniqChar(String s) {
Map<Character, Integer> dict = new HashMap<Character, Integer>();
HashSet<Character> hSet = new HashSet<Character>();
for(int i = 0; i<s.length();i++)
{
char c = s.charAt(i);
if(hSet.contains(c))
{
continue;
}
if (!dict.containsKey(c))
{
dict.put(c, i);
}
else
{
dict.remove(c);
hSet.add(c);
}
}
if(dict.size() == 0)
{
return -1;
}
int min = Integer.MAX_VALUE;
for (Integer value : dict.values()) {
min = value<min ? value : min;
}
return min;
}
}
方案2
class Solution {
public int firstUniqChar(String s) {
int min = Integer.MAX_VALUE;
for (char c = 'a'; c <= 'z'; c++)
{
int tmp = s.indexOf(c);
if(tmp!=-1 && tmp == s.lastIndexOf(c))
{
min = tmp<min ? tmp : min;
}
}
min = min == Integer.MAX_VALUE ? -1 : min;
return min;
}
}
Python3 解決方案
方案1
from string import ascii_lowercase as alc
class Solution:
def firstUniqChar(self, s: str) -> int:
m = math.pow(10,5); #min
for c in alc:
try:
tmp = s.index(c)
tmp2 = s.rindex(c)
except:
continue;
if tmp == tmp2:
m = tmp if tmp<m else m
return -1 if m == math.pow(10,5) else m
JavaScript 解決方案
方案1
/**
* @param {string} s
* @return {number}
*/
var firstUniqChar = function(s) {
var min = 10**5;
for (var i = 97; i <= 122; i++) {
var c = String.fromCharCode(i);
var tmp = s.indexOf(c);
if(tmp!=-1 && tmp == s.lastIndexOf(c))
{
min = tmp<min ? tmp : min;
}
}
min = min == 10**5 ? -1 : min;
return min;
};
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"cc175a72d9"};
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"cc175a72d9","uagb_grid_ajax_nonce":"7cac865027"};
( function() {
let elements = document.querySelectorAll( '.uagb-post-grid.uagb-block-f8e8b1ea .uagb-post-pagination-wrap a' );
elements.forEach(function(element) {
element.addEventListener("click", function(event){
event.preventDefault();
const link = event.target.getAttribute('href').match( /\/page\/\d+\// )?.[0] || '';
const regex = /\d+/; // regular expression to match a number at the end of the string
const match = link.match( regex ) ? link.match( regex )[0] : 1; // match the regular expression with the link
const pageNumber = parseInt( match ); // extract the number and parse it to an integer
window.UAGBPostGrid._callAjax({"btnBorderTopWidth":1,"btnBorderLeftWidth":1,"btnBorderRightWidth":1,"btnBorderBottomWidth":1,"btnBorderTopLeftRadius":30,"btnBorderTopRightRadius":30,"btnBorderBottomLeftRadius":30,"btnBorderBottomRightRadius":30,"btnBorderStyle":"none","overallBorderColor":"","block_id":"f8e8b1ea","categories":"6","displayPostExcerpt":false,"displayPostComment":false,"displayPostImage":false,"imgSize":"medium","linkBox":false,"align":"center","orderBy":"rand","excludeCurrentPost":true,"postPagination":true,"pageLimit":0,"imageRatio":"2-3","imgEqualHeight":true,"UAGHideMob":true,"UAGHideTab":true,"UAGResponsiveConditions":true,"btnBorderLink":true,"btnBorderRadiusLink":true,"overallBorderLink":true,"overallBorderRadiusLink":true,"inheritFromTheme":true,"postType":"post","postDisplaytext":"No post found!","taxonomyType":"category","postsToShow":6,"enableOffset":false,"postsOffset":0,"displayPostDate":true,"excerptLength":15,"displayPostAuthor":false,"displayPostTitle":true,"displayPostTaxonomy":false,"hideTaxonomyIcon":true,"taxStyle":"default","displayPostTaxonomyAboveTitle":"withMeta","imgPosition":"top","bgOverlayColor":"#000000","overlayOpacity":"50","displayPostLink":true,"newTab":false,"ctaText":"Read More","inheritFromThemeBtn":false,"buttonType":"primary","btnHPadding":"","btnVPadding":"","columns":3,"tcolumns":2,"mcolumns":1,"width":"wide","order":"desc","rowGap":20,"rowGapTablet":20,"rowGapMobile":20,"columnGap":20,"bgType":"color","bgColor":"#f6f6f6","titleTag":"h4","titleFontSize":"","titleFontSizeType":"px","titleFontFamily":"","titleLineHeightType":"em","titleLoadGoogleFonts":false,"metaColor":"","highlightedTextColor":"#fff","highlightedTextBgColor":"#3182ce","metaFontSize":"","metaFontSizeType":"px","metaFontFamily":"","metaLineHeightType":"em","metaLoadGoogleFonts":false,"excerptColor":"","excerptFontSize":"","excerptFontSizeType":"px","excerptFontFamily":"","excerptLineHeightType":"em","excerptLoadGoogleFonts":false,"displayPostContentRadio":"excerpt","ctaBgType":"color","ctaBgHType":"color","ctaFontSize":"","ctaFontSizeType":"px","ctaFontFamily":"","ctaLineHeightType":"em","ctaLoadGoogleFonts":false,"paddingTop":20,"paddingBottom":20,"paddingRight":20,"paddingLeft":20,"contentPadding":20,"ctaBottomSpace":0,"ctaBottomSpaceTablet":0,"ctaBottomSpaceMobile":0,"imageBottomSpace":15,"titleBottomSpace":15,"metaBottomSpace":15,"excerptBottomSpace":25,"contentPaddingUnit":"px","rowGapUnit":"px","columnGapUnit":"px","excerptBottomSpaceUnit":"px","paginationSpacingUnit":"px","imageBottomSpaceUnit":"px","titleBottomSpaceUnit":"px","metaBottomSpaceUnit":"px","ctaBottomSpaceUnit":"px","paddingBtnUnit":"px","mobilePaddingBtnUnit":"px","tabletPaddingBtnUnit":"px","paddingUnit":"px","mobilePaddingUnit":"px","tabletPaddingUnit":"px","isPreview":false,"taxDivider":", ","titleLetterSpacing":"","titleLetterSpacingType":"px","metaLetterSpacing":"","metaLetterSpacingType":"px","ctaLetterSpacing":"","ctaLetterSpacingType":"px","excerptLetterSpacing":"","excerptLetterSpacingType":"px","useSeparateBoxShadows":true,"boxShadowColor":"#00000070","boxShadowHOffset":0,"boxShadowVOffset":0,"boxShadowBlur":"","boxShadowSpread":"","boxShadowPosition":"outset","boxShadowColorHover":"","boxShadowHOffsetHover":0,"boxShadowVOffsetHover":0,"boxShadowBlurHover":"","boxShadowSpreadHover":"","boxShadowPositionHover":"outset","borderWidth":"","borderStyle":"none","borderColor":"","borderRadius":"","blockName":"post-grid","equalHeight":true,"paginationBgActiveColor":"#e4e4e4","paginationActiveColor":"#333333","paginationBgColor":"#e4e4e4","paginationColor":"#777777","paginationMarkup":"","paginationLayout":"filled","paginationBorderColor":"#888686","paginationBorderSize":1,"paginationSpacing":20,"paginationAlignment":"left","paginationPrevText":"\u00ab Previous","paginationNextText":"Next \u00bb","layoutConfig":[["uagb\/post-image"],["uagb\/post-taxonomy"],["uagb\/post-title"],["uagb\/post-meta"],["uagb\/post-excerpt"],["uagb\/post-button"]],"post_type":"grid","equalHeightInlineButtons":false,"paginationType":"ajax","isLeftToRightLayout":false,"wrapperTopPadding":"","wrapperRightPadding":"","wrapperLeftPadding":"","wrapperBottomPadding":"","wrapperTopPaddingTablet":"","wrapperRightPaddingTablet":"","wrapperLeftPaddingTablet":"","wrapperBottomPaddingTablet":"","wrapperTopPaddingMobile":"","wrapperRightPaddingMobile":"","wrapperLeftPaddingMobile":"","wrapperBottomPaddingMobile":"","wrapperPaddingUnit":"px","wrapperPaddingUnitTablet":"px","wrapperPaddingUnitMobile":"px","wrapperPaddingLink":false,"wrapperAlign":"row","wrapperAlignPosition":"center","extended_widget_opts_block":{},"extended_widget_opts":{},"extended_widget_opts_state":"","extended_widget_opts_clientid":"","dateUpdated":""}, pageNumber, 'f8e8b1ea');
});
});
} )();
ai_front = {"insertion_before":"BEFORE","insertion_after":"AFTER","insertion_prepend":"PREPEND CONTENT","insertion_append":"APPEND CONTENT","insertion_replace_content":"REPLACE CONTENT","insertion_replace_element":"REPLACE ELEMENT","visible":"VISIBLE","hidden":"HIDDEN","fallback":"FALLBACK","automatically_placed":"Automatically placed by AdSense Auto ads code","cancel":"Cancel","use":"Use","add":"Add","parent":"Parent","cancel_element_selection":"Cancel element selection","select_parent_element":"Select parent element","css_selector":"CSS selector","use_current_selector":"Use current selector","element":"ELEMENT","path":"PATH","selector":"SELECTOR"};