Longest Substring Without Repeating Characters
短信预约 -IT技能 免费直播动态提醒
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
- public class T {
- public static void main(String[] args) {
- String s1 = "pwwkew";
- String s2 = "abcabcbb";
- String s3 = "dvdf";
- String s4 = "bbbb";
- System.out.println(lengthOfLongestSubstring(s1));
- }
- public static int lengthOfLongestSubstring(String s) {
- int maxlength = 0;
- int leftIndex = 0;
- int rightIndex = 0;
- while (rightIndex < s.length()) {
- char target = s.charAt(rightIndex);
- int mark = -1;
- for (int i = leftIndex; i < rightIndex; i++) {
- if (s.charAt(i) == target) {
- mark = i + 1;
- break;
- }
- }
- if (mark != -1) {
- if ((rightIndex - leftIndex) > maxlength) {
- maxlength = (rightIndex - leftIndex);
- }
- leftIndex = mark;
- rightIndex = mark;
- } else {
- rightIndex++;
- }
- }
- if ((rightIndex - leftIndex) > maxlength) {
- maxlength = (rightIndex - leftIndex);
- }
- return maxlength;
- }
- }
另附网上的答案一则.
http://www.cnblogs.com/grandyang/p/4480780.html
- public class Solution {
- public int lengthOfLongestSubstring(String s) {
- int[] m = new int[256];
- Arrays.fill(m, -1);
- int res = 0, left = -1;
- for (int i = 0; i < s.length(); ++i) {
- left = Math.max(left, m[s.charAt(i)]);
- m[s.charAt(i)] = i;
- res = Math.max(res, i - left);
- }
- return res;
- }
- }
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341