Java | Leetcode Java题解之第316题去除重复字母

avatar
作者
筋斗云
阅读量:0

题目:

题解:

class Solution {     public String removeDuplicateLetters(String s) {         boolean[] vis = new boolean[26];         int[] num = new int[26];         for (int i = 0; i < s.length(); i++) {             num[s.charAt(i) - 'a']++;         }          StringBuffer sb = new StringBuffer();         for (int i = 0; i < s.length(); i++) {             char ch = s.charAt(i);             if (!vis[ch - 'a']) {                 while (sb.length() > 0 && sb.charAt(sb.length() - 1) > ch) {                     if (num[sb.charAt(sb.length() - 1) - 'a'] > 0) {                         vis[sb.charAt(sb.length() - 1) - 'a'] = false;                         sb.deleteCharAt(sb.length() - 1);                     } else {                         break;                     }                 }                 vis[ch - 'a'] = true;                 sb.append(ch);             }             num[ch - 'a'] -= 1;         }         return sb.toString();     } }

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!